26

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 something after_create for 3 models?

Thanks

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

1 Answers1

58

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.

Srikala B
  • 3
  • 2
jpemberthy
  • 7,473
  • 8
  • 44
  • 52
  • Strange, for some reason it's not working. I added a debugger logger and nothing's getting written. Is there some other step required to get the Observer to kick in? – AnApprentice Oct 01 '10 at 01:35
  • 4
    K turns out it needs to be "ActiveRecord::Observer" and it needs to be defined in the application.rb file in the config directory. – AnApprentice Oct 01 '10 at 01:43
  • 4
    You can leave off "Observer" in the class name of the generate script: "rails g observer Auditor" generates AuditorObserver. – tee Oct 21 '11 at 20:41