Migration
class CreateTrackChangesTables < ActiveRecord::Migration
def change
create_table :track_changes_snapshots do |t|
t.references :record, :polymorphic => true
t.text :state
t.timestamps
end
create_table :track_changes_diffs do |t|
t.references :record, :polymorphic => true
t.text :from
t.text :to
t.string :action
t.string :changes_by
t.timestamps
end
end
endTrackChanges::Configuration.cascade_destroy = false # Controls whether tracked changes are deleted when the record is deleted. Can be set to false if an audit trail of destroyed records is desired. Default: true
TrackChanges::Configuration.serialize = false # Controls whether tracked changes are serialized as YAML before being written to the database. Can be set to false if the `state`, `from`, and `to` columns are JSON datatype instead of text. Default: trueclass Person < ActiveRecord::Base
tracks_changes # may also pass an options hash
endPerson.snapshot_all # Initialize snapshots for existing records so the next time the record is saved a diff can be generated.
Person.tracked_change(status: "approved", assigned_to: "user_123") # Returns a list of diffs where specific attributes changed to the specified values.By default all model attributes are tracked, except the primary_key, usually id, created_at, and updated_at.
:onlyaccepts a field name or array of field names to track instead of the default fields:exceptaccepts a field name or array of field names to ignore:methodsaccepts a field name or array of field names to track in addition to the default fields:track_timestampsaccepts a boolean, enabling or disabling tracking ofcreated_atandupdated_at:track_primary_keyaccepts a boolean, enabling or disabling tracking of the model's primary key:track_locking_columnaccepts a boolean, enabling or disabling tracking of the model's locking column
Changes can be attributed to a particular source. The source is saved as a string
in the :changes_by column of the record. If given an instance of ActiveRecord::Base,
the record's id will be used.
# Model-level attribution
person.track_changes_by = 'Joe Changems'
person.save
# Block-level attribution
TrackChanges.with_changes_attributed_to 'Joe Changems' do
person.save
end
# Controller-level attribution
class MyController < ApplicationController
attribute_changes_to :current_user
end