开发者

Rails 3 Observer -- looking to learn how to implement an Observer for multiple models

开发者 https://www.devze.com 2023-01-18 07:32 出处:网络
I\'d like to add an Auditor Observer which does an action anytime after_create for 3 models (books, characters, authors)...

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

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

How do I create an Auditor Observer that does som开发者_StackOverflowething after_create for 3 models?

Thanks


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

First, you need to generate your observer:

rails g observer Auditor

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 

In application.rb add

config.active_record.observers = :auditor_observer

And It should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消