Rails Observer

Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class.

In my project,I have to track certain action (create and update) of user on particular model basically i am maintaining some kind of log, or audit trails.In my application eventlog model has attribute user and body.

class EventlogObserver < ActiveRecord::Observer
  observe :model1, :model2

  def after_create(record)
    @eventlog = Eventlog.new
    @eventlog.body = record.class.to_S+“Created at”+Time.now
  def after_update(record)
    @eventlog = Eventlog.new
    @eventlog.body = record.class.to_S+“Updated at”+Time.now

This eventlog_observer.rb is stored in app/model

Now Configuration add following line in /config/environment.rb config.active_record.observers = :eventlog_observer

In rails there are various callbacks on which you trigger some common behaviour

  • after_create
  • after_update
  • after_save
  • after_destroy
  • before_create
  • before_update
  • before_save
  • before_destroy

and many more you can also refer from http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

For further reference http://api.rubyonrails.org/classes/ActiveRecord/Observer.html


Leave a reply:

Your email address will not be published.

Site Footer