Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple values for collection_select

I am trying to have the following HTML code in my form:

 <select name="user[language_ids][]">
    <option value="">Please select</option>
    <option value="1" selected="selected">English</option>
    <option value="2">Spanish</option>
  </select>

  <select name="user[language_ids][]">
    <option value="">Please select</option>
    <option value="1" selected="selected">English</option>
    <option value="2">Spanish</option>
  </select>

To allow the User to select two languages when he signs up.

I have tried with this:

<%= f.label :languages %>
<%= f.collection_select(:language_ids, Language.all, :id, :name) %>
<%= f.collection_select(:language_ids, Language.all, :id, :name) %>

And also with this:

<%= f.label :languages %>
<%= f.collection_select(:language_ids[], Language.all, :id, :name) %>
<%= f.collection_select(:language_ids[], Language.all, :id, :name) %>

After revieweing the answers, I have tried with this:

<%= collection_select(:user, :language_ids, Language.all, :id, :name, {}, {:name => 'user[language_ids][]' }) %>
    <%= collection_select(:user, :language_ids, Language.all, :id, :name, {}, {:name => 'user[language_ids][]' }) %>

But the problem here is that both of the selects have the same ID and also, they are not associated with the form builder f

Any thoughts on the best way to do so?

like image 234
Hommer Smith Avatar asked Dec 31 '12 04:12

Hommer Smith


2 Answers

Try,

<%= f.collection_select(:language_ids, Language.all, :id, :name,{}, {:multiple => true}) %>
like image 114
shweta Avatar answered Nov 15 '22 07:11

shweta


You can create a collection of fields by using fields_for.
The two select will have the same id but collection_select takes an optional hash containings html options where you can set a custom id.

<%= f.fields_for :language_ids do |language| %>
  <%= language.collection_select(nil, Language.all, :id, :name,
        {include_blank: "Please select", selected: 1},
        {id: :user_language_id_1}) %>
  <%= language.collection_select(nil, Language.all, :id, :name,
        {include_blank: "Please select", selected: 1},
        {id: :user_language_id_2}) %>
<% end %>

generates the following output:

<select id="user_language_id_1" name="user[language_ids][]">
  <option value="">Please select</option>
  <option value="1" selected="selected">English</option>
  <option value="2">Spanish</option>
</select>

<select id="user_language_id_2" name="user[language_ids][]">
  <option value="">Please select</option>
  <option value="1" selected="selected">English</option>
  <option value="2">Spanish</option>
</select>
like image 32
user1003545 Avatar answered Nov 15 '22 07:11

user1003545