本文介绍了Rails 3 Observer-寻找学习如何为多个模型实现Observer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一个Auditor Observer,它可以在after_create之后针对3种模型(书籍,人物,作者)随时执行操作...

I'd like to add an Auditor Observer which does an action anytime after_create for 3 models (books, characters, authors)...

我最近听说了Observer功能,但是找不到有关该功能的任何文档. Rails 3支持吗?

I recently heard of the Observer capability but can't find any documentation on the ability. Is it support in Rails 3?

我如何创建对3个模型执行after_create操作的Auditor Observer?

How do I create an Auditor Observer that does something after_create for 3 models?

谢谢

推荐答案

Rails 观察者很不错,您可以在单个观察者

Rails observers are sweet, You can observe multiple models within a single observer

首先,您需要生成观察者:

First, you need to generate your observer:

rails g observer Auditor

然后,在新的audit_observer.rb文件中,定义要observe的模型,然后添加after_create回调.

Then, in your fresh auditor_observer.rb file define the models you wish to observe and then add the after_create callback.

 class AuditorObserver < ActiveRecord::Observer
   observe :model_foo, :model_bar, :model_baz

   def after_create(record)
    #do something with `record`
   end
 end 

在application.rb中添加

In application.rb add

config.active_record.observers = :auditor_observer

它应该可以工作.

这篇关于Rails 3 Observer-寻找学习如何为多个模型实现Observer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 19:34