[Rails] select-multiple for has_many association

Michael Schuerig michael at schuerig.de
Wed Aug 9 19:27:44 GMT 2006


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.

  <select id="person_task_ids" multiple="multiple" 
   name="person[tasks][]">
    <option value="1">Do something</option>
    ...
  </select>


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

  <select id="person_tasks" multiple="multiple"
   name="person[tasks]">
    <option value="1">Do something</option>
    ...
  </select>

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

  <select id="person_task_ids" multiple="multiple"
   name="person[task_ids]">
    <option value="1">Do something</option>
    ...
  </select>

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 Schuerig
mailto:michael at schuerig.de
http://www.schuerig.de/michael/


More information about the Rails mailing list