opensoul.org

acts_as_audited

July 21, 2006 acts_as_audited, plugin, popular, rails, ruby

NOTE: This article is out of date. Visit the project on Github or the mailing list for up-to-date information.

acts_as_audited is an Active Record plugin that logs all modifications to your models in an audits table. It uses a polymorphic association to store an audit record for any of the model objects that you wish to have audited. The audit log stores the model that the change was on, the “action” (create, update, destroy), a serialzied hash of the changes, and optionally the user that performed the action.

Auditing in Rails

If you’re using acts_as_audited within Rails, you can simply declare which models should be audited. acts_as_audited can also automatically record the user that made the change if your controller has a current_user method.

class ApplicationController < ActionController::Base
  audit User, List, Item
protected
  def current_user
    @user ||= User.find(session[:user])
  end
end

Customizing

To get auditing outside of Rails, or to customize which fields are audited within Rails, you can explicitly declare acts_as_audited on your models. The :except option allows you to specify one or more attributes that you don’t want to be saved in the audit log.

class User < ActiveRecord::Base
  acts_as_audited :except => [:password, :credit_card_number]
end

Installation

You can grab the plugin by running:

script/plugin install git://github.com/collectiveidea/acts_as_audited.git

Run the migration generator and migrate to add the audits table.

script/generate audited_migration add_audits_table
rake db:migrate

Upgrading

Those upgrading from version 0.2 need to add 2 fields the audits table:

add_column :audits, :user_type, :string
add_column :audits, :username, :string

I am Brandon Keepers. I build Internet things, usually with Ruby or JavaScript. I work at GitHub and live in Holland, MI.