9

I have a small rails app. I want to put audit trail in it. Basically when a new user is added. it will insert a row in AuditTrailUsers table with the new user_id created and logged in users' user_id.

I am thinking about using rails callback before_save for this. However, I am not sure if that will work.

Imagine I have model/Users.rb and model/AuditTrailUser.rb

class User < ActiveRecord::Base
    validates_presence_of :userid, :password
        before_save :insert_audit

  def self.authenticate(userid, password)
        user = self.find_by_userid_and_password(userid, password)       
    user
  end

  ##implement insert_audit

end

How can I implement insert_audit so that it takes in a user id (of logged in user) so that it can pass it to AuditTrailUser when calling AuditTrailUser.create(...).

If I pass in logged in user's user id...then will I have to explicitly call before_save every where...

I am new to rails.

groovynoob
  • 343
  • 1
  • 3
  • 8

1 Answers1

13

Use the Audited gem to log all changes to your Rails models.

AndrewKS
  • 3,603
  • 2
  • 24
  • 33
groovynoob
  • 343
  • 1
  • 3
  • 8
  • 2
    There is a better alternative to acts_as_audited Vestal versions plugin(http://github.com/laserlemon/vestal_versions). Discussed on SO http://stackoverflow.com/questions/2323505/how-to-keep-track-of-model-history-with-mapping-table-in-ruby-on-rails – so_mv Jun 30 '11 at 00:17
  • 2
    Another interesting one is paper_trail https://github.com/airblade/paper_trail. Railscasts link '255-undo-with-paper-trail' http://railscasts.com/episodes/255-undo-with-paper-trail – so_mv Jun 30 '11 at 01:13
  • 1
    The Audited gem is still pretty good and has been kept largely up to date. It also has some nice features that the others lack. – Brendon Muir Feb 05 '14 at 01:04