My model looks like this:
after_create :foobar
after_update :foobar
def foobar
update_attributes(:foo => 'bar')
end
Whenever I create an object. It calls foobar (after_create callback). But it also automatically triggers the after_update callback.
Basically, when I create an object its calling foobar twice.
How can I prevent this?
In
after_createyou’re callingupdate_attributes()which triggers theafter_updatecallback.Basically you’re calling it twice. You need to figure out what the proper flow is for your program, and make it such that
foobaronly gets called once. Right now, the code you’ve written is executing as designed.One suggestion would be using
before_[action]attributes instead to modify the fields in the incoming object. That way the object only gets saved once. The way you’ve written it, new objects get saved twice – once when they’re created, and once when they’re updated viaupdate_attributes.I see that this is example code, but I’m not sure how, in
after_update, since you explicitly make ANOTHER update, how this isn’t getting wrapped up in an infinite loop. Might be able to give a better answer if you post actual code.