# Select-multiple for has\_many association

**URL:** <https://www.ruby-forum.com/t/select-multiple-for-has-many-association/64631>\
**Category:** Rails\
**Created:** [August 15, 2006, 2:11pm UTC](https://www.ruby-forum.com/t/select-multiple-for-has-many-association/64631 "2006-08-15T14:11:55Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![wickie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/ba9def/32.png) [@wickie](https://www.ruby-forum.com/u/wickie)\
**Post date:** [August 15, 2006, 2:11pm UTC](https://www.ruby-forum.com/t/select-multiple-for-has-many-association/64631/1 "2006-08-15T14:11:55Z")

</div>

I haven’t looked into this for several months, but there still doesn’t  
seem to be an obvious way to generate a HTML select element for  
choosing multiple items to be set for a has\_many association.

Do something  
…

Let’s see. There’s a handy helper method that results in code like this,  
when used straightforwardly

\<%= collection\_select :person, :tasks,  
Task.find(:all), :id, :description, {},  
:multiple =\> true %\>

Here’s the resulting HTML

Do something  
…

Unfortunately, none of the options gets selected. When the form is  
submitted, the resulting params are

“person” =\> { “tasks” =\> “1” }

Only the first selected item is transferred and, anyway, “1” is not a  
task, it is a task id, so this won’t work.

Here’s the next attempt:

\<%= collection\_select :person, :task\_ids,  
Task.find(:all), :id, :description, {},  
:multiple =\> true %\>

Well, that blows up immediately as there is not such method as  
person#task\_ids. But we can add it manually:

class Person \< ActiveRecord::Base  
def task\_ids  
tasks.map(&:id)  
end  
end

Now we get

Do something  
…

That was almost good. How about this, then?

\<%= collection\_select :person, :task\_ids,  
Task.find(:all), :id, :description, {},  
:multiple =\> true,  
:name =\> ‘person[task\_ids][]’ %\>

Ah yes, that’s it. But why does it have to be so complicated?

Michael

–  
Michael S.  
[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
[http://www.schuerig.de/michael/](http://www.schuerig.de/michael/)
