【问题标题】:Rails: Multiple dropdown menus collection_selectRails:多个下拉菜单 collection_select
【发布时间】:2015-08-12 13:04:11
【问题描述】:

这里的 Super Rails n00b:目前我有一个带有以下代码的表单:

<%= f.collection_select :account_ids, @accounts, :id, :name, include_blank: true %>

它目前可以按我想要的方式工作,但现在我想要多个下拉菜单,以便我可以选择多个帐户。我不希望多选出现在同一个下拉列表中。

如果我这样做:

<%= f.collection_select :account_ids, @accounts, :id, :name, include_blank: true %>
<%= f.collection_select :account_ids, @accounts, :id, :name, include_blank: true %>
<%= f.collection_select :account_ids, @accounts, :id, :name, include_blank: true %>

只有最后一个选择出现在参数中。我怎样才能使参数看起来像这样:

"journal"=>{"account_ids"=>["1","2","3"]}

collection.select 可以这样做还是我应该使用不同的东西?任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: ruby-on-rails drop-down-menu collection-select


    【解决方案1】:

    您需要添加一个选项:multiple

    <%= f.collection_select :account_ids, @accounts, 
                            :id, :name, { include_blank: true },
                             { multiple: true } %>
    

    注意::multiple- 如果设置为 true,则选择将允许多选。

    我写了一个小sn-p来测试它。我的代码:

    <%= form_for @track, url: fetch_path do |f| %>
      <%= f.collection_select :label, @tracks, :id, :title, {include_blank: true}, {multiple: true} %>
    <% end %>
    

    这是页面:

    或者,如果你真的想复制:

    <% klass = f.object.class.model_name.param_key %>
    <%= f.collection_select :account_ids, @accounts, :id, :name, { include_blank: true } , { name: "#{klass}[account_ids][]" } %>
    

    上面一行写3遍。

    【讨论】:

    • 您好,Arup,感谢您的回复。但是,我只想制作多个下拉菜单,不能在同一个菜单中选择多个选项。
    • @ckg61386 你正在做多项选择,但最多3。您可以使用javascript 处理。如果您想要最大的N 值选择,那么复制相同的下拉值 N 次是没有意义的......
    【解决方案2】:

    如果您的参数名称以“[]”结尾,那么所有具有该名称的输入将被整理到具有该名称的数组中。

    所以,你的选择标签(在 html 中)会像

    <select name="account_ids[]"><option>...
    

    要使用collection_select 帮助器,请尝试

    <%= f.collection_select :account_ids, @accounts, :id, :name, {include_blank: true}, {:name => 'account_ids[]'} %>
    

    【讨论】:

    • 乍一看,这实际上给了它单独的 account_id 参数,但我希望它出现在日志参数中,例如:“journal”=>{accounts: ["1","2", "3"]}
    • 啊,那么名称应该是“journal[accounts][]”。将字符串放在方括号内使其成为哈希结构而不是数组。这些可以以任何你想要的方式组合成嵌套数组和散列的任何数据结构。
    • 而且,在你原来的问题中,你说你想要像:journal =&gt; {:account_ids =&gt; [1,2,3]} 这样的参数,(我错过了,对不起),所以如果你想要account_ids 而不是accounts(就像你在你的注释)那么名称属性应该是"journal[account_ids][]"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多