【发布时间】:2012-07-18 00:59:46
【问题描述】:
我有一个 Rails 应用程序,它经常使用回调。所以我有很多函数在多个模型中被调用:after_create 和 :after_commit。
我想知道我现在的做法是不是最好的。
基本上我有以下场景:
Class Parent < ActiveRecord::Base
has_many :children
after_create :first_function
after_commit :last_function
def first_function
if !self.processed?
self.children.create(:name => "Richard The Lion Heart")
self.processed = true
self.save!
end
end
def last_function
if self.processed?
if !self.processing?
self.process
self.save!
self.processing = true
self.save!
end
end
end
end
所以你可以看到整个事情依赖于一些奇怪的双重布尔检查,因为否则每次更新模型时都会调用 second_function 并且它可以由函数本身更新,因此函数会被重复调用。
总的来说,这导致我必须为每个回调引入一个新的布尔检查以触发。它有效,但我不认为它很优雅。我错过了什么?
【问题讨论】:
-
这可以在 before_save 之前完成吗?