有一种方法可以同样处理`after_save`和`after_destroy`“吗?

时间:2012-01-15 18:08:41

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 callback

我正在使用Rails 3.1.0,我想知道是否可以“同等”地处理after_saveafter_destroy回调。也就是说,我需要为after_saveafter_destroy回调运行相同的方法。

此时我必须单独处理这些回调,即使这些回调达到同样的目的:

after_save do |record|
  # Make a thing
end

after_destroy do |record|
  # Make the same thing as in the 'after_save' callback
end

那么,有一种方法可以同等地处理after_saveafter_destroy吗?

3 个答案:

答案 0 :(得分:29)

而不是阻止将after_saveafter_destroy模型的方法名称作为符号。

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

答案 1 :(得分:7)

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

  private
  def my_callback
    #Do stuff
  end
end

答案 2 :(得分:6)

要在保存和销毁后执行相同的回调,您可以使用after_commit

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

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