Delayed saving of records assigned to association?

4 views
Skip to first unread message

Jonathan Viney

unread,
Jan 22, 2007, 10:32:21 PM1/22/07
to rubyonra...@googlegroups.com
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.

Francois Beausoleil

unread,
Jan 23, 2007, 9:25:13 AM1/23/07
to rubyonra...@googlegroups.com
Hello Jonathan,

What you want is a transaction:

2007/1/22, Jonathan Viney <jonatha...@gmail.com>:

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 !
--
François Beausoleil
http://blog.teksol.info/
http://piston.rubyforge.org/

Reply all
Reply to author
Forward
0 new messages