Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_collection_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.

like image 606
marcamillion Avatar asked Apr 12 '11 13:04

marcamillion


2 Answers

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) %>
like image 194
DanneManne Avatar answered Nov 19 '22 15:11

DanneManne


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) %>
like image 20
bigsolom Avatar answered Nov 19 '22 15:11

bigsolom