Habtm doesn't save old IDs

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

not sure if this is your problem or not but if you are using Rails 1.0
this might be your issue.
http://dev.rubyonrails.org/changeset/3332

“Fixed that saving a model with multiple habtm associations would only
save the first one.”

Hm… the description doesn’t sound like my problem, but I guess it
could definitely be a bug in rails. Is it possible to get a newer
version of the gem? Or do I need to use svn to get an updated version?

-Payton

This sounds exactly like my problem:

http://dev.rubyonrails.org/ticket/3692

This is similar:

http://dev.rubyonrails.org/ticket/3604

As is this:

http://dev.rubyonrails.org/ticket/3259

Looks like a recurring problem for lots of people. It looks like the
solution is to manually patch activerecord… but is there a better way?

-Payton

i haven’t done it yet but you can do this to get the the EdgeRails with
all the fixs.
Peak Obsession though not always an
option if you are wanting to deploy an app.

Yes!

Revision 3332 makes it work! Wow, I spent a whole day assuming I had
done something wrong there. Thank you guys.

What’s the release schedule (if any) for activerecord? That is, any
idea when this patch will be in the gem?

-Payton

Have you tried edge rails?

Looks like a fix has been applied.

http://dev.rubyonrails.org/ticket/3244

Bob S.
http://www.railtie.net/