There is a way to handle `after_save` and `after_destroy` “equally”?

为君一笑 提交于 2019-12-01 15:16:39

Instead of a block give after_save and after_destroy a method name of your model as a symbol.

class ModelName < AR
  after_save :same_callback_method
  after_destroy :same_callback_method

  def same_callback_method
    # do the same for both callbacks
  end
end

To execute the same callback after both saving and destroying, you can use after_commit

after_commit do |record|
  # Is called after creating, updating, and destroying.
end

http://apidock.com/rails/ActiveRecord/Transactions/ClassMethods/after_commit

class Foo < ActiveRecord::Base
  after_save :my_callback
  after_destroy :my_callback

  private
  def my_callback
    #Do stuff
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!