【问题标题】:There is a way to handle `after_save` and `after_destroy` "equally"?有办法“平等地”处理“after_save”和“after_destroy”吗?
【发布时间】:2012-02-10 22:10:37
【问题描述】:

我正在使用 Rails 3.1.0,我想知道是否可以“平等地”处理 after_save 和 after_destroy 回调。也就是说,我需要为after_save 和after_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_save 和after_destroy?

【问题讨论】:

  • 从两者调用相同的方法?
  • @Dave Newton - 方法实际上是一样的。
  • 我明白 - 这就是为什么我说从两者调用相同的方法,无论您是使用帖子中的表单,还是从答案中的方法参考。

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


【解决方案1】:

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

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

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

【讨论】:

  • 根据我的经验,这仅在触发事件的操作被包装在事务块中时才有效,至少在 Rails >= 3.2 中。否则不会调用它。
  • 这不一样。 after_save 中的事务尚未提交,after_commit 中的事务已提交。
  • *_commit 仅在事务块中触发。当你save时它不会触发。
  • 在 2018 年的 Rails 5 上,无论是否存在事务块,都会触发 *_commit。所以这个答案很好!
【解决方案2】:

给after_save和after_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

【讨论】:

  • 一个类是用class关键字定义的,而不是def关键字。
【解决方案3】:
class Foo < ActiveRecord::Base
  after_save :my_callback
  after_destroy :my_callback

  private
  def my_callback
    #Do stuff
  end
end

【讨论】:

  • 根据用例,protected 可能优于 private
猜你喜欢
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 2020-09-16
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 2011-01-29
  • 2019-11-17
相关资源
最近更新 更多