2011-09-12 25 views
2
  1. 在index.html.erb,我希望有一個鏈接,看起來像每個大學以下:應用 - $ 25使用在.erb文件的link_to,拼接語法

  2. 我想要的價格根據college.undergrad_app_fee的值顯示更改。

這是我試過的,但它不起作用。也許有一種特殊的連接語法來將明確的「應用 - 」與價格結合起來,或者我需要以某種方式轉義,或者有什麼特別的方法可以用link_to來做到這一點?

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

回答

12

使用字符串插補語法:

<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_iflink_to_unless,它們應該比較直接的使用。

處理貨幣格式化的nil情況有點棘手。您可以使用||運營商來執行此操作。

兩種方法結合將使這樣的:

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

使用軌道控制檯是測試不同傭工的行爲的好辦法。您可以通過helper對象訪問它們,例如:

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

哇,很好的答案 - 也快!謝謝。我會將你的答案標記爲正確答案。如果你喜歡它,我有一個後續問題:如果college.undergrad_app_fee爲空,我希望它顯示$ 0。如果college.application_url爲空,我不希望它成爲一個鏈接。有任何想法嗎? – Adam

+0

我更新了我的答案,這應該做你想要的。 –