在after_commit中更新属性时防止无限循环,:on =>:创建 [英] Prevent infinite loop when updating attributes within after_commit, :on => :create

查看:22
本文介绍了在after_commit中更新属性时防止无限循环,:on =>:创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我需要在 after_commit 期间更新属性时,我创建了一个无限回调循环,:on =>:创建.但是,仅当我需要在此回调期间更新对象的属性时才会发生这种情况.有没有办法防止这种情况?我可以以某种方式强制模型重新加载自己,以便它知道它正在执行更新而不是创建吗?

I create an infinite callback loop when I need to update an attribute during an after_commit, :on => :create. It only occurs if I need to update an attribute of the object during this callback, though. Is there a way to prevent this? Can I somehow force a model to reload itself so it knows that it is performing an update rather than a create?

class Doc < ActiveRecord::Base
  after_commit :generate, :on => :create

  ...

  def generate
    # some logic here that requires this model to be saved in the db

    self.update_attributes(:filename => filename) # Infinite loop begins here.
  end
end

推荐答案

您可以使用方法 update_column 跳过模型的所有回调:

You can use the method update_column that will skip all callbacks of your model:

self.update_column(:filename, filename)

或者你可以使用方法 update_all,遵循相同的行为

Or you could use the method update_all, wich follows the same behavior

self.class.where('id = ?', self.id).update_all(:filename => filename)

最后但并非最不重要的是,我个人最喜欢的:

And last but not least, my personal favorite:

self.filename = filename
self.send(:update_without_callbacks)

这个很清楚地表明所有回调都被忽略了,这很有帮助

This one makes it pretty clear that all callbacks are been ignored, what is very helpful

此外,作为另一种选择,如果您只想在新的记录已保存

Also, as a different alternative, you coud use after_create instead of after_commit if you want to run the generate method only when a new record is saved

这篇关于在after_commit中更新属性时防止无限循环,:on =>:创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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