使用 after_save 回调修改同一个对象而不再次触发回调(递归) [英] Using the after_save callback to modify the same object without triggering the callback again (recursion)

查看:42
本文介绍了使用 after_save 回调修改同一个对象而不再次触发回调(递归)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我向 ActiveRecord 模型添加 after_save 回调,并且在该回调中我使用 update_attribute 更改对象,则会再次调用回调,因此会发生堆栈溢出"(呵呵,无法抗拒).

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?

谢谢!

推荐答案

一种解决方法是在类中设置一个变量,并在 after_save 中检查其值.

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

  1. 先检查一下.(如果变量)
  2. 在调用 update_attribute 之前将其指定为false"值.
  3. 调用 update_attribute.
  4. 将其分配给真"值.
  5. 结束

这样,它只会尝试保存两次.这可能会两次访问您的数据库,这可能会也可能不会.

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

我有一种模糊的感觉,即内置了一些东西,但这是一种相当万无一失的方法,可以防止几乎所有应用程序中的特定递归点.我还建议再次查看代码,因为很可能您在 after_save 中所做的任何事情都应该在 before_save 中完成.有时这不是真的,但这种情况相当罕见.

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.

这篇关于使用 after_save 回调修改同一个对象而不再次触发回调(递归)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆