dollarhino
dollarhino

Reputation: 45

Multiple attribute in collection_select in Rails

I am trying to allow for multiple value selection from a collection in a Rails form. The field is working but does not allow for multiple selections (once an alternative option is selected the previously selected is unselected). I am using Bootstrap CDN, which I don't presume is causing issues, but I may be wrong?

Can you see anything wrong with this code?

  <div class="field form-group row">
      <%= f.label :industry_ids, class:"col-sm-3"%>
      <%= f.collection_select(:industry_ids, Industry.all, :id, :name, {:multiple => true}, size: Industry.all.length) %>
    </div>

Thanks for your help.

Upvotes: 1

Views: 2745

Answers (1)

Adam Berman
Adam Berman

Reputation: 794

I believe your problem is that you're putting {:multiple => true} in the wrong options hash. The method signature for collection_select looks like this:

collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

multiple is an html attribute of the select tag itself (here's a doc), so you want to pass that to html_options, not options. Your code looks like this:

f.collection_select(:industry_ids, Industry.all, :id, :name, {:multiple => true}, size: Industry.all.length)

Where Industry.all is the collection, :id is the value_method, and :name is the text_method, which means { :multiple => true } is getting passed to options, not html_options. Move it to the second hash and you should be fine.

Upvotes: 1

Related Questions