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.
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)
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
-
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.
-
add migration generator to create conventionally-named log table (i.e. ticket_changes) to schema