具有属性更改条件的多个 after_update 回调仅触发第一个
Multiple after_update callbacks with attribute change conditions are triggering only the first one
具有属性更改条件的多个 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
没有被触发。
您可以只使用一个带有 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
确保检查回调的 return 值。如果 before_*
或 after_*
ActiveRecord 回调 return 为 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.
具有属性更改条件的多个 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
没有被触发。
您可以只使用一个带有 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
确保检查回调的 return 值。如果 before_*
或 after_*
ActiveRecord 回调 return 为 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.