开发者

Tracking field changes with rails observers

开发者 https://www.devze.com 2023-03-28 02:28 出处:网络
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

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
开发者_如何学JAVA#  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


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

0

精彩评论

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

关注公众号