【问题标题】:How do I define values in options_for_select?如何在 options_for_select 中定义值?
【发布时间】:2015-03-07 22:53:55
【问题描述】:

我有这个 options_for_select 调用:

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

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

我如何编辑上面的代码来得到这个?谢谢!

【问题讨论】:

    标签: ruby-on-rails select erb options


    【解决方案1】:

    实际上有一个专门针对集合的助手,options_from_collection_for_select 就是专门处理这种情况的。

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

    【讨论】:

      【解决方案2】:

      您应该直接提供您想要用作选项值和 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"}) %>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多