我有以下片段:
class Product
after_commit :do_something, on: %i(update create)
def do_something
if # update
...
else # create
...
end
end
end
如何知道什么事件触发了此处的提交后?
请不要告诉我在提交后有 2 个:
after_commit :do_something_on_update, on: :update
after_commit :do_something_on_create, on: :create
最佳答案
ActiveRecord uses transaction_include_any_action?
:
def do_something
if transaction_include_any_action?([:create])
# handle create
end
if transaction_include_any_action?([:update])
# handle update
end
end
一个事务可以包含多个操作。如果 :create
和 :update
都可以在程序的同一个事务中使用,则需要两个 if
,而不是 if
/其他
。
关于ruby-on-rails - 知道什么事件触发了 ActiveRecord 模型的 after_commit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37100451/