This plugin for the state machine gem (see github.com/pluginaweek/state_machine) adds support for keeping an audit trail for any state machine. Having an audit trail gives you a complete history of the state changes in your model. This history allows you to investigate incidents or perform analytics, like: “How long does it take on average to go from state a to state b?”, or “What percentage of cases goes from state a to b via state c?”
Note: while the state_machine gem integrates with multiple ORMs, this plugin is currently limited to the following ORM backends:
-
ActiveRecord
-
Mongoid
It should be easy to add new backends by looking at the implementation of the current backends. Pull requests are welcome!
First, make the gem available by adding it to your Gemfile
, and run bundle install
:
gem 'state_machine-audit_trail'
Create a model/table that holds the audit trail. The table needs to have a foreign key to the original object, an “event” field, a “from” state field, a “to” state field, and a “created_at” timestamp that stores the timestamp of the transition. This gem comes with a Rails 3 generator to create a model and a migration like that.
rails generate state_machine:audit_trail [<model> <state_attribute>]
For a model called “Model”, and a state attribute “state”, this will generate the ModelStateTransition model and an accompanying migration. Not giving any parameters will generate the single table model.
Next, tell your state machine you want to store an audit trail:
class Model < ActiveRecord::Base state_machine :state, :initial => :start do store_audit_trail ...
If you audit trail use a single polymorfic table as your model provide it using the :polymorphic
option:
class Model < ActiveRecord::Base state_machine :state, :initial => :start do store_audit_trail :polymorphic => true ...
If your audit trail model does not use the default naming scheme, provide it using the :to
option:
class Model < ActiveRecord::Base state_machine :state, :initial => :start do store_audit_trail :to => 'ModelAuditTrail' ...
That’s it! The plugin will register an after_transition
callback that is used to log all transitions. It will also log the initial state if there is one.
This plugin is written by Jesse Storimer and Willem van Bergen for Shopify. Mongoid support was contributed by Siddharth (github.com/svs). It is released under the MIT license (see LICENSE).