如何在Rails 3中的options_from_collection_for_select中自定义菜单选项?

mar*_*ion 4 ruby-on-rails-3

在我看来,我有这个:

<%
@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 />
Run Code Online (Sandbox Code Playgroud)

这产生以下结果:

<select id="Plan" name="Plan"><option value="1">Gecko</option> 
<option value="2" selected="selected">Iguana</option> 
</select>
Run Code Online (Sandbox Code Playgroud)

但是,我希望它能够产生以下选项:

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

括号中的价格是plan.amount.

Dan*_*nne 17

您可以在模型中创建一个返回您想要呈现的值的方法:

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) %>
Run Code Online (Sandbox Code Playgroud)