所有模型的 ActiveRecord 全局回调 [英] ActiveRecord Global Callbacks for all Models

查看:20
本文介绍了所有模型的 ActiveRecord 全局回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 RoR 应用程序中有大约 40 个模型.我想为所有模型设置 after_save 回调.一种方法是将其添加到所有模型中.由于此回调具有相同的代码要运行,有没有办法全局定义它一次,以便为所有模型调用它.

I have around 40 models in my RoR application. I want to setup a after_save callback for all models. One way is to add it to all models. Since this callback has the same code to run, is there a way to define it globally once so that it gets invoked for all models.

我没有运气就试过了:

class ActiveRecord::Base

  after_save :do_something

  def do_something
    # .... 
  end
end

如果我在单个模型中执行相同的代码.

Same code works if I do it in individual models.

谢谢,伊姆兰

推荐答案

你应该为此使用观察者:

You should use observers for this:

class AuditObserver < ActiveRecord::Observer      

  observe ActiveRecord::Base.send(:subclasses)

  def after_save(record)
    AuditTrail.new(record, "UPDATED")
  end
end

要激活观察者,请将其列在 config/application.rb 文件的 config.active_record.observers 配置设置中.

In order to activate an observer, list it in the config.active_record.observers configuration setting in your config/application.rb file.

config.active_record.observers = :audit_observer

注意

在 Rails 4 中,观察者功能从核心中移除.使用 https://github.com/rails/rails-observers gem.

In Rails 4, the observer feature is removed from core. Use the https://github.com/rails/rails-observers gem.

这篇关于所有模型的 ActiveRecord 全局回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆