在 index.html.erb 中,我希望每所大学都有一个如下所示的链接:Apply - $25
我希望显示的价格根据 college.undergrad_app_fee 的值而变化。
这是我试过的方法,但它不起作用。也许有一种特殊的串联语法可以将显式的“应用 -”与价格结合起来,或者我需要以某种方式转义 <%= %>,或者有一种特殊的方法可以使用 link_to 来完成此操作?
<td><%= link_to 'Apply - ' college.undergrad_app_fee, college.application_url %></td>
最佳答案
使用字符串插值语法:
<td><%= link_to "Apply - #{college.undergrad_app_fee}", college.application_url %></td>
作为奖励,如果您只有原始价格,您可以使用 number_to_currency
格式化它:
<td><%= link_to "Apply - #{number_to_currency(college.undergrad_app_fee)}", college.application_url %></td>
跟进:
对于条件链接,使用 link_to_if或 link_to_unless ,它们应该相对简单易用。
处理货币格式的 nil
情况有点棘手。您可以使用 ||
运算符来执行此操作。
结合这两种方法会得到这个:
<td><%= link_to_if college.application_url, "Apply - #{number_to_currency(college.undergrad_app_fee || 0)}", college.application_url %></td>
使用 Rails 控制台是测试不同助手行为的好方法。您可以通过 helper
对象访问它们,例如:
> helper.number_to_currency(12)
=> "12,00 €"
> nil || 0
=> 0
> 12 || 0
=> 12
关于ruby-on-rails - 在 .erb 文件中使用 link_to,串联语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7392805/