如何在options_for_select中定义值?

时间:2015-03-07 22:53:55

标签: ruby-on-rails select erb options

我有这个options_for_select电话:

    <%= f.select(:agents, options_for_select(@agents), {},{multiple: true, size: 10, :id => "agents"}) %>

目前数据库中只有2个代理,但它们显示为#<Agent:0x007fc1b121c490>格式。我希望它们显示为@agent.name,值为@agent.id

如何编辑上面的代码才能获得此代码?谢谢!

2 个答案:

答案 0 :(得分:2)

实际上有一个专门用于集合的帮助器,options_from_collection_for_select正是为了处理这种情况。

<%= f.select(:agents, options_from_collection_for_select(@agents, 'id', 'name'), {},{multiple: true, size: 10, :id => "agents"}) %>

答案 1 :(得分:1)

您应该直接提供要用作选项值和ID的内容:
<%= f.select(:agents, options_for_select(@agents.map{ |agent| [agent.name, agent.id]}), {},{multiple: true, size: 10, :id => "agents"}) %>
参考documentation API
此外,您可能希望选择当前值:
<%= f.select(:agents, options_for_select(@agents.map{ |agent| [agent.name, agent.id]}, @current_agent), {},{multiple: true, size: 10, :id => "agents"}) %>