1

Say I have a many-to-many relationship defined as follows:

In my user model :

class User < ActiveRecord::Base
 attr_accessible :userName (...) 
 has_and_belongs_to_many :groups
end

In my group model :

class Group < ActiveRecord::Base
  attr_accessible :groupName (...)
  has_and_belongs_to_many :users
end

I added to my users controller in update and create:

@user.group_ids = Group.find(params[:group_ids]) if params[:group_ids]

The user form contains a multiselect list to choose the groups for each user (among other criteria that actually work):

<%= select_tag("group_ids[]", options_for_select(Group.find(:all).collect { |gro| [gro.groupName, gro.id] }, @user.groups.collect { |gro| gro.id}), {:multiple=>true, :size=>15}) %>

When I create or update a user, everything looks to work fine, but whatever the choice I make in the picklist, it adds to the user the wrong group (always the group with id=1). I tried with has_many_through and migrated the database but had the issue too.

Do you know how to make the assignment happen ?

pb2q
  • 58,613
  • 19
  • 146
  • 147

1 Answers1

0

Instead of the select tag, you can use the f.select form helper detailed in: Rails 3: Multiple Select with has_many through associations

Also, there are two-sided multi select that work perfectly as stated in: two sided multi select that works with Rails 3

I recommend the one from http://loudev.com/, you just need to use:

<%= f.select(:country, "country_id", Country.all.collect {|c| [ c.name, c.id ] }, {:include_blank => false}, {:class => "multiselect", :multiple => "multiple"}) %>

And add the following Javascript to your view:

<script>
$(document).ready(function (){
     $('.multiselect').multiSelect(); 
});
</script>
Community
  • 1
  • 1
rfernand
  • 41
  • 1
  • 5