【问题标题】:Know what event triggered the after_commit of an ActiveRecord model知道什么事件触发了 ActiveRecord 模型的 after_commit
【发布时间】:2016-05-08 13:38:15
【问题描述】:

我有以下sn-p:

class Product
 after_commit :do_something, on: %i(update create)

 def do_something
   if # update
     ...
   else # create
     ...
   end
 end
end

这里怎么知道是什么事件触发了after commit?

请不要告诉我在提交后有 2 个:

after_commit :do_something_on_update, on: :update
after_commit :do_something_on_create, on: :create

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord rails-activerecord


【解决方案1】:

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 在您的程序中的同一个事务中都可能出现,则您需要两个ifs,而不是if/else

【讨论】:

    【解决方案2】:

    查看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
    

    【讨论】:

      猜你喜欢
      • 2015-04-18
      • 2012-02-20
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      相关资源
      最近更新 更多