How to create a full Audit log in Rails for every table?

谁说胖子不能爱 提交于 2019-11-28 16:54:00

I had a similar requirement on a recent project. I ended using the acts_as_audited gem, and it worked great for us.

In my application controller I have line like the following

audit RunWay,RunWayModel,OtherModelName

and it takes care of all the magic, it also keeps a log of all the changes that were made and who made them-- its pretty slick.

Hope it helps

Harish Shetty

Use the Vestal versions plugin for this:

Refer to this screen cast for more details. Look at the similar question answered here recently.

Vestal versions plugin is the most active plugin and it only stores delta. The delta belonging to different models are stored in one table.

class User < ActiveRecord::Base
  versioned
end

# following lines of code is from the readme    
>> u = User.create(:first_name => "Steve", :last_name => "Richert")
=> #<User first_name: "Steve", last_name: "Richert">
>> u.version
=> 1
>> u.update_attribute(:first_name, "Stephen")
=> true
>> u.name
=> "Stephen Richert"
>> u.version
=> 2
>> u.revert_to(10.seconds.ago)
=> 1
>> u.name
=> "Steve Richert"
>> u.version
=> 1
>> u.save
=> true
>> u.version
=> 3

Added this monkey-patch to our lib/core_extensions.rb

ActiveRecord::Associations::HasManyThroughAssociation.class_eval do 
  def delete_records(records)
    klass = @reflection.through_reflection.klass
    records.each do |associate|
      klass.destroy_all(construct_join_attributes(associate))
    end
  end
end

It is a performance hit(!), but satisfies the requirement and considering the fact that this destroy_all doesn't get called often, it works for our needs--though I am going to check out acts_as_versioned and acts_as_audited

You could also use something like acts_as_versioned http://github.com/technoweenie/acts_as_versioned
It versions your table records and creates a copy every time something changes (like in a wiki for instance)
This would be easier to audit (show diffs in an interface etc) than a log file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!