在after_commit prevent无限循环更新时的属性,:在=> :创建 [英] Prevent infinite loop when updating attributes within after_commit, :on => :create
问题描述
我创建了一个无限循环的回调时,我需要一个 after_commit中更新的属性:上=> :创建
。它只发生,如果我需要这个回调过程中更新对象的属性,虽然。有没有一种方法,以prevent呢?我能以某种方式强制模型重新加载自身,以便它知道它正在执行更新,而不是创造?
类文档<的ActiveRecord :: Base的
after_commit:生成,:对=> :创建
...
DEF产生
#一些逻辑在这里,要求该模型被保存在数据库
self.update_attributes(:文件名=>文件名)#无限循环从这里开始。
结束
结束
您可以使用的方法 update_column
将跳过模型的所有回调:
self.update_column(:文件名,文件名)
或者你可以使用的方法 update_all
,至极遵循同样的行为
self.class.where('ID =?',self.id).update_all(:文件名=>文件名)
最后但并非最不重要的,我个人最喜欢的:
self.filename =文件名
self.send(:update_without_callbacks)
这才让它pretty的明确,所有的回调被忽视了,什么是非常有帮助的。
此外,作为一个不同的选择,你coud使用 after_create
而不是 after_commit
如果你想运行生成
方法,只有当一个新的记录被保存
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
You can use the method update_column
that will skip all callbacks of your model:
self.update_column(:filename, filename)
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 prevent无限循环更新时的属性,:在=&GT; :创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!