How do I customize the menu option in options_from_collection_for_select in Rails 3?
I have this in my view:
<%
@plan = Plan.limit(4).all
plan ||= Plan.find(params[:plan_id])
%>
<%= select_tag "Plan", options_from_coll开发者_JAVA技巧ection_for_select(@plan, 'id', 'name', plan.id) %><br />
That produces the following:
<select id="Plan" name="Plan"><option value="1">Gecko</option>
<option value="2" selected="selected">Iguana</option>
</select>
However, I would like it to produce the following options:
<select id="Plan" name="Plan"><option value="1">Gecko ($50)</option>
<option value="2" selected="selected">Iguana ($99)</option>
</select>
Where the price in brackets is plan.amount
.
You could create a method in your model which returns the value you want to present:
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) %>
options_from_collection_for_select
also accepts the text method as lambda so you can write the custom method in the view instead of model incase you have some view specific code that you don't want to pollute the model with.
<%= select_tag "Plan", options_from_collection_for_select(@plan, 'id', lambda { |plan| "#{plan.name} (#{plan.amount})")}, plan.id) %>
精彩评论