Topic: using collection_select with arrays

If I have a many to many relationships, and I'm using collection_select to add one entry to the list:

Currently, I have to use a temp variable for the collection_select process, and then append it to the list like that:

collection_select(:unit, :tempweapon_id, @available_weapons, :id, :name)
and then     @unit.weapons << Weapon.find(:first, :conditions => "id=#{temp_weapon_id}")

is there a more direct way to use the collection_select for a many_to_many relationships?


Re: using collection_select with arrays

You can enable multiple selection on the select box for handling the many-to-many relationship. See this post for details on how to do that.

Does that solve your problem?

Railscasts - Free Ruby on Rails Screencasts

Re: using collection_select with arrays

thank you,
This link helped a lot, especially as I had some problems with checkboxes, but in the case I was thinking about, multiple collection_select would not work: In my case, there would be too many choiches to have all of them appear in a multiple collection select.

I was planning to use javascript to make the user select a category first to limit the number of choices): I think in the multiple collection select exemple, that would remove the items previously selected that which are not in the sub-category.

Last edited by Galdred (2006-08-20 20:01:45)

Re: using collection_select with arrays

It should work, you'll just need more logic on the controller side. But then you are getting more complicated than your original solution. If you're satisfied with adding one item at a time, your first solution is probably best. The second line in your original post could be shortened though:

# instead of:
@unit.weapons << Weapon.find(:first, :conditions => "id=#{temp_weapon_id}")

# do:
@unit.weapons << Weapon.find(temp_weapon_id)

# this might work too, but I'm not positive
@unit.weapon_ids << temp_weapon_id

Last edited by ryanb (2006-08-20 20:25:50)

Railscasts - Free Ruby on Rails Screencasts