Waz*_*ery 7 ruby activerecord ruby-on-rails ruby-on-rails-4 rails-activerecord
我有以下代码段:
class Product
after_commit :do_something, on: %i(update create)
def do_something
if # update
...
else # create
...
end
end
end
Run Code Online (Sandbox Code Playgroud)
如何知道在此提交后触发了什么事件?
提交之后请不要告诉我有2个:
after_commit :do_something_on_update, on: :update
after_commit :do_something_on_create, on: :create
Run Code Online (Sandbox Code Playgroud)
ActiveRecord 使用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
Run Code Online (Sandbox Code Playgroud)
一个事务可以包括多个动作。如果在程序中的同一个事务中都可以使用:create和 ,:update则需要两个ifs,而不是if/ else。
只检查 id 的 previous_changes 怎么样,如果是nil,那就意味着我们正在做create
def do_something
id_changes = self.previous_changes[:id]
# Creating
if id_changes && id_changes.first.nil?
...
else # Updating
...
end
end
Run Code Online (Sandbox Code Playgroud)