Using the after_save callback to modify the same object without triggering the callback again (recursion)

ruby-on-rails

Solution

One workaround is to set a variable in the class, and check its value in the after_save.

- Check it first. (if var)

- Assign it to a 'false' value before calling update_attribute.

- call update_attribute.

- Assign it to a 'true' value.

- end

This way, it'll only attempt to save twice. This will likely hit your database twice, which may or may not be desirable.

I have a vague feeling that there's something built in, but this is a fairly foolproof way to prevent a specific point of recursion in just about any application. I would also recommend looking at the code again, as it's likely that whatever you're doing in the after_save should be done in before_save. There are times that this isn't true, but they're fairly rare.

Problem

If I add an after_save callback to an ActiveRecord model, and on that callback I use update_attribute to change the object, the callback is called again, and so a 'stack overflow' occurs (hehe, couldn't resist). Is it possible to avoid this behavior, maybe disabling the callback during it's execution? Or is there another approach? Thanks!

Original source

Related problems