Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Add meaningful names for belongs_to associations to Rails 2.1 model object dirty changes to help with rolling your own history/audit logger.
Ruby
branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
.gitignore
CHANGELOG
README.rdoc
Rakefile
expressive_record.gemspec
init.rb

README.rdoc

Expressive Record

Add meaningful names for belongs_to associations to Rails 2.1 model object dirty changes (dev.rubyonrails.org/changeset/9127) to help with rolling your own history/audit logger.

Install

script/plugin install git://github.com/lukewendling/expressive_record.git

or

sudo gem install lukewendling-expressive_record --source http://gems.github.com

create a migration for the audit table (see USAGE)

Usage

ActiveRecord 2.1 introduces dirty changes; the ability to query a model object to track attribute changes before the record is saved using #changes, #changed, etc.

However, belongs_to associations are cached simply as foreign key changes, so Ticket#changes yields something like {“status_id” => [“111”, “222”]}, which isn't especially helpful when rolling your own audit logger.

Expressive Record turns association (foreign key) changes into meaningful terms when the changes are saved to your audit table.

class Ticket < ActiveRecord::Base
  include ExpressiveRecord

  has_many :ticket_changes

  # pass in the name of your audit table (optional)
  express_changes :ticket_changes

end

express_changes adds a before_update callback to your model that inserts changes into an audit table with the following schema:

class CreateTicketChanges < ActiveRecord::Migration
  def self.up
    create_table "ticket_changes", :force => true do |t|
      t.integer  "ticket_id",      :null => false
      t.string   "attribute_type", :null => false
      t.text     "old_value"
      t.text     "new_value"
      t.timestamps
    end
  end
end

If using a before_update callback in subclasses, be sure to call 'super' as needed:

class A
  # a before_update callback is auto-magically added
  express_changes
end

class A < B
  def before_update
    self.status = 'New' # do this before auditing
    super # now insert changes into audit log
  end
end

Limitations

  • the current implementation assumes that all belongs_to foreign keys use Rails conventional names, like user_id or status_id. if you are connecting to a legacy db with fk's like customerID or whatever, this won't work.

TODO

  • add migration generator to create conventionally-named log table (i.e. ticket_changes) to schema

Something went wrong with that request. Please try again.