如何在创建提交后编写rails活动记录回调类

xmjla07d  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(260)

我想使用类回调来重用差异模型的回调,我写道 after_create_commit 方法,但当我在模型中使用它时,模型将被保存,它将生成

undefined method `after_commit`

例如:
回调类

class TrackingRecord
  def after_create_commit(record)
    // do thing
  end

  def after_update_commit(record)
    // do thing
  end
end

模型

class SomeModel < ApplicationRecord
  after_create_commit TrackingRecord.new
  after_update_commit TrackingRecord.new

  // other stuff
end

在类中创建/更新提交回调后如何编写?或者如果我必须定义 after_commit 我如何区分哪些是创建的,哪些是更新的?
非常感谢。

uklbhaso

uklbhaso1#

rails的 after_commit 在创建、更新或销毁记录后调用。
对于每种情况,您都可以使用 after_create , after_update , after_destroy 回调或使用 on 选择 after_commit .

class SomeModel < ApplicationRecord
  # after_create, after_update
  after_create :do_after_create
  after_update :do_after_update

  # OR using on option
  after_commit :do_after_create, on: :create
  after_commit :do_after_update, on: :update

  def do_after_create
     # Using your class
     TrackingRecord.new.after_create_commit(self)
     # or do something here
  end

  def do_after_update
     # Using your class
     TrackingRecord.new.after_update_commit(self)
     # or do something here
  end

end

希望能有帮助:d

相关问题