DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Using A Mutiple Collection Select Form Helper With Habtm Or Has Many Associations In Rails

07.30.2007
| 22067 views |
  • submit to reddit
        // where user has and belongs to many roles

# in your view
<%= collection_select :user, :role_ids, Role.find(:all, :order => 'name ASC'), :id, :name, { :selected => @user.role_ids }, { :multiple => true, :name => 'user[role_ids][]' } -%>
    

Comments

Snippets Manager replied on Tue, 2011/03/29 - 7:42am

The :selected option should be in the last option hash, at least in recent versions of Rails. Also, if working with a form_for or fields_for object (f) you can skip the :name option, it seems to be set appropriately. There's no need for accepts_nested_attributes_for - this should work out of the box with a has_and_belongs_to_many relation. Example view code: = f.collection_select :delivery_method_ids, DeliveryMethod.inactive, :id, :to_s_with_price, {}, { :selected => @user.delivery_method_ids, :multiple => true }