Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tracking field changes with rails observers

I am trying to figure out a way to log the changes when someone updates an object. Right now my observer will store all of the current values but I am lost on how to determine which fields changed and how to store them in my feeds db.

For sake of simplicity here is a sample model and observer. My goal is to track which field was updated and store it in my Feed db. I am open to adding new fields to my db if they are needed. Let me know if you have any questions.

Model

# Table name: milestones
#
#  id            :integer         not null, primary key
#  name          :string(255)
#  project_id    :integer
#  target_date   :datetime

Observer tracking the change

class MilestoneObserver < ActiveRecord::Observer

    def after_update(milestone)
        f = Feed.new(
          :action => milestone.name, 
          :project_id => milestone.project_id, 
          :updated_by_id => "Jordan")
        f.save
    end 
end
like image 773
jlarry Avatar asked Aug 15 '11 22:08

jlarry


1 Answers

To know which fields have changed, do:

object.changes

See nice article here: http://ryandaigle.com/articles/2008/3/31/what-s-new-in-edge-rails-dirty-objects

like image 189
apneadiving Avatar answered Oct 05 '22 11:10

apneadiving