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

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

问题描述

我有大约40款在我的RoR应用程序。我想设置一个after_save的回调所有车型。一种方法是将其添加到所有模型。由于这个回调有相同的code运行,有没有办法来定义它在全球范围一次,以便它被调用的所有型号。

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

同code的作品,如果我这样做,在个别机型。

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

注意

在轨道4,观测特征是从核心移除。使用 https://github.com/rails/rails-observers 的宝石。

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

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

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