我有一個Rails應用程序,使用回調了很多..這樣我有很多函數調用:after_create和:after_commit在多個模型中。如何在Rails中組織複雜的回調?
我想知道我現在做的方式是否最好。
基本上我有以下情形:
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? – cpuguy83 2012-07-18 01:58:44