Delayed saving of records assigned to association?

At the moment, the following code causes the specified groups to be updated, even though the save is unsuccessful.

class Person < AR::Base
belongs_to :group
end

class Group < AR::Base
has_many :people

def validate
errors.add_to_base “ERROR”
end
end

g = Group.find(:first)
g.person_ids = [1,2] # The database is updated here, unless g is a new record
g.save # false

This is a bit misleading, as the changes to the group_id of persons 1 and 2 will be saved.

A better way would be to only set the foreign keys of the people objects initially, and then save the changes to the database with an after_save callback on the Group model. Would a patch to change this behaviour be accepted, being that it is not completely backwards compatible, or is there a reason for this implementation?

Cheers,
Jonathan.

Hello Jonathan,

What you want is a transaction:

Group.transaction do

g = Group.find(:first)
g.person_ids = [1,2] # The database is updated here, unless g is a new
record
g.save # false

end

Be sure to use g.save! to ensure an exception is thrown, or else the
transaction will complete successfully.

Hope that helps !