Model “One”
class One < ActiveRecord::Base
before_save :do_stuff
private
def do_stuff
two = Two.find(8)
two.field2 = 'Value'
two.save!
end
end
Model “Two”
class Two < ActiveRecord::Base
before_save :do_stuff
private
def do_stuff
one = One.find(7)
one.field2 = 'SomeValue'
one.save!
end
end
Executing:
two = Two.find(1)
two.somefield = 'NewVal'
two.save!
Infinite loop will start. What would be most ruby-on-rails way to implement two models that must change each other on before_save callback?
On the hopefully rare occasions you need to do this, you might want to disable your
before_savefilter using anattr_accessoror move it to anafter_saveblock to avoid looping.For example:
You’d disable the trigger on at least one of them:
Things like this are always very ugly, so try and avoid it unless you can think of no other way. If you need it, make sure you’ve written enough unit tests to ensure it won’t lock into an endless loop under some edge cases.