Rails: Multiple dropdown menus collection_select

橙三吉。 提交于 2021-02-17 05:05:32

问题


Super Rails n00b here: Currently I have a form with the following code:

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

and it currently works how I want it to but now I would like to have multiple drop down menus so I can select multiple accounts. I do not want the multiple select to be on the same dropdown.

If I do this:

<%= 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 %>

only the last selection appears in the params. How can I make it so the params would look like this:

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

Can collection.select do this or should I be using something different? Any help would be greatly appreciated. Thanks!


回答1:


You need to add one option :multiple :

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

Note: :multiple- If set to true the selection will allow multiple choices.

I wrote a little snippet to test it. My code :

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

Here is the page :

drodown

Or, if you really want to duplicate:

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

Write the above line 3 times.




回答2:


If your parameter name ends in "[]", then all inputs with that name will be collated into an array with that name.

So, your select tag (in html) will be like

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

and to make this using the collection_select helper, try

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


来源:https://stackoverflow.com/questions/30533381/rails-multiple-dropdown-menus-collection-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!