I’m sure I’m not getting something. I have Users, and I have Groups.
Each User has_and_belongs_to_many :groups and each Group
has_and_belongs_to_many :users.
When I add a user, I want to apply a bunch of groups (like tags) to the
user (manually, without acts_as_taggable).
Here’s User#create:
@user = User.new(params[:user])
@user.groups = params[:user][:group_names].split(/\s+/).collect do
|group|
Group.find(:first, :conditions => [“name = ?”, group]) ||
Group.new({:name => group})
end
@user.save
Groups that have not yet been created are created and their associations
to the user are saved in groups_users. Groups that already exist,
however, are not added to groups_users.
The further oddity is that User#groups=() does add previously existing
Groups, if I call it on a User object that has already been added to
the database.
Here’s an entry from the logs:
before save, groups=[#<Group:0x40710a9c @attributes={“name”=>“one”,
“id”=>“1”}>, #<Group:0x4066e654 @new_record=true,
@attributes={“name”=>“eight”}>]
This Group gets added:
#<Group:0x4066e654 @new_record=true, @attributes={“name”=>“eight”}>
This Group does not:
#<Group:0x40710a9c @attributes={“name”=>“one”, “id”=>“1”}>
Why? Validation? I checked and there’s no errors before or after the
save.
-Payton