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:[email protected]
http://www.schuerig.de/michael/