Problem with touch and autosave options

Hello,

I face a problem using the new Rails 2.3.3 :touch option along with
the :autosave option.

My app have three models: User, Group and Membership

class User < ActiveRecord::Base

attribute: name

has_many :memberships, :dependent => :destroy
accepts_nested_attributes_for :memberships, :allow_destroy =>
true, :reject_if => proc { |attributes| attributes
[‘group_id’].blank? }

Having “accepts_nested_attributes_for :memberships”

makes :autosave option true for the “has_many :memberships”
association.
has_many :groups, :through => :memberships
end

class Membership < ActiveRecord::Base

attributes: user_id, group_id, content

belongs_to :user, :touch => true
belongs_to :group, :touch => true
end

class Group < ActiveRecord::Base

attribute: name

has_many :memberships, :dependent => :destroy
has_many :users, :through => :memberships
end

You can see my problem in this console script:

user = User.find 1
User Load (1.6ms) SELECT * FROM “users” WHERE (“users”.“id” = 1)
±—±-----±------------------------±------------------------+
| id | name | created_at | updated_at |
±—±-----±------------------------±------------------------+
| 1 | joe | 2009-07-09 20:47:52 UTC | 2009-07-23 21:59:33 UTC |
±—±-----±------------------------±------------------------+
1 row in set

user.memberships
Membership Load (1.2ms) SELECT * FROM “memberships” WHERE
(“memberships”.user_id = 1)
±—±---------±---------±--------±------------------------
±------------------------+
| id | content | group_id | user_id | created_at |
updated_at |
±—±---------±---------±--------±------------------------
±------------------------+
| 1 | the boss | 1 | 1 | 2009-07-21 22:59:21 UTC |
2009-07-23 21:59:33 UTC |
±—±---------±---------±--------±------------------------
±------------------------+
1 row in set

user.name = “bill”
=> “bill”

user.save!
User Update (0.7ms) UPDATE “users” SET “updated_at” = ‘2009-07-23
21:59:56’, “name” = ‘bill’ WHERE “id” = 1
User Load (1.0ms) SELECT * FROM “users” WHERE (“users”.“id” = 1)
User Update (0.3ms) UPDATE “users” SET “updated_at” = ‘2009-07-23
21:59:56’ WHERE “id” = 1
Group Load (0.7ms) SELECT * FROM “groups” WHERE (“groups”.“id” =

Group Update (0.2ms) UPDATE “groups” SET “updated_at” =
‘2009-07-23 21:59:56’ WHERE “id” = 1
=> true

As you can see, even if I did not change the user membership, when I
save the user, it will touch the group of the membership.
Can I prevent this unexpected behaviour, or is it a bug of the new
touch feature with autosave?

It does not happen without accepts_nested_attributes_for (ie
without :autosave) or if I don’t load user.memberships before saving
user, but in my app I need accepts_nested_attributes_for and the user
memberships are loaded in the User controller edit method.

Thanks by advance for your help :slight_smile:

Regards,
Florent