具有属性更改条件的多个after_update回调仅触发第一个回调。
class Article < ActiveRecord::Base
after_update :method_1, :if => proc{ |obj| obj.status_changed? && obj.status == 'PUBLISHED' }
after_update :method_2, :if => proc{ |obj| obj.status_changed? && obj.status == 'PUBLISHED' && obj.name == 'TEST' }
...
end
更新模型对象时会触发 method_1
:
Article.last.update_attributes(status: 'PUBLISHED', name: 'TEST')
未触发method_2
。
答案 0 :(得分:2)
您可以使用一个带有if...end
块的回调来过滤您希望在每种情况下执行的操作。
class Article < ActiveRecord::Base
after_update :method_1, :if => proc{ |obj| obj.status_changed? && obj.status == 'PUBLISHED' }
...
def method_1
if self.name == 'TEST'
# stuff you want to do on method_2
else
# stuff you want to do on method_1
end
end
end
答案 1 :(得分:0)
确保检查回调的返回值。如果before_*
或after_*
ActiveRecord回调返回false,则链中的所有后续回调都将被取消。
来自docs(请参阅取消回调)
If a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled.