In a particular class that extends ActiveRecord::Base, I need to update a different ActiveRecord object whenever this one is created. Is it safe to override the save method and do the following in the save?
def save
super
other = self.other
other.name = self.name
other.save!
end
I’m worried about potential transaction related issues. I assume this would all be 1 transaction, if any part fails, everything is rolled back?
Is there a particular reason why you wouldn’t use the hooks provided for this purpose?
You’ve got
after_create,after_save,after_update,before_create,before_save,before_update– and a bunch of others. Wouldn’t one of those be suitable?In fact, given what you’ve said, it sounds like
before_saveis what you want, as you can catch any errors that occur whilst saving the second model and prevent the first one from being saved (by returning false from thebefore_savecall).