2011-04-12 56 views
3

我有這個在我看來:如何在Rails 3中自定義options_from_collection_for_select中的菜單選項?

<% 
@plan = Plan.limit(4).all 
plan ||= Plan.find(params[:plan_id]) 

%> 

<%= select_tag "Plan", options_from_collection_for_select(@plan, 'id', 'name', plan.id) %><br /> 

產生如下:

<select id="Plan" name="Plan"><option value="1">Gecko</option> 
<option value="2" selected="selected">Iguana</option> 
</select> 

不過,我想它產生以下選項:

<select id="Plan" name="Plan"><option value="1">Gecko ($50)</option> 
<option value="2" selected="selected">Iguana ($99)</option> 
</select> 

那裏的價格在括號內是plan.amount

回答

15

您可以創建模型中的一個方法,它返回要呈現的值:

class Plan < ActiveRecord::Base 
    ... 

    def display_name 
    "#{self.name} (#{self.amount})" 
    end 
end 

# View 
<%= select_tag "Plan", options_from_collection_for_select(@plan, 'id', 'display_name', plan.id) %> 
+0

這太棒了。謝謝。 – marcamillion 2011-04-12 15:05:48

1

options_from_collection_for_select還接受文本方法拉姆達這樣你就可以櫃面寫在視圖,而不是模型的定製方法你有一些你不想污染模型的特定代碼。

<%= select_tag "Plan", options_from_collection_for_select(@plan, 'id', lambda { |plan| "#{plan.name} (#{plan.amount})")}, plan.id) %> 
相關問題