Adam
Adam

Reputation: 464

Using link_to in an .erb file, concatenation syntax

  1. In index.html.erb, I want a link that looks like the following for each college: Apply - $25

  2. I want the price displayed to change based on the value of college.undergrad_app_fee.

This is what I've tried, but it doesn't work. Perhaps there's a special concatenation syntax to combine the explicit 'Apply -' with the price, or I need to escape <%= %> somehow, or there's a special way to do this with link_to?

   <td><%= link_to 'Apply - ' college.undergrad_app_fee, college.application_url %></td>

Upvotes: 2

Views: 4110

Answers (1)

Benoit Garret
Benoit Garret

Reputation: 13675

Use the string interpolation syntax:

<td><%= link_to "Apply - #{college.undergrad_app_fee}", college.application_url %></td>

As a bonus, if you only have the raw price, you can format it using number_to_currency:

<td><%= link_to "Apply - #{number_to_currency(college.undergrad_app_fee)}", college.application_url %></td>

Follow up:

For conditional links, use link_to_if or link_to_unless, they should be relatively straightforward to use.

Handling the nil case for the currency formatting is a bit trickier. You can use the || operator to do it.

Combining the two methods would give this:

<td><%= link_to_if college.application_url, "Apply - #{number_to_currency(college.undergrad_app_fee || 0)}", college.application_url %></td>

Using the rails console is a good way to test the behaviours of the different helpers. You can access them through the helper object, for example:

> helper.number_to_currency(12)
 => "12,00 €"
> nil || 0
 => 0
> 12 || 0
 => 12

Upvotes: 12

Related Questions