2014-02-25 12:05:47 -05:00
# PaperTrail [![Build Status](https://img.shields.io/travis/airblade/paper_trail/master.svg)](https://travis-ci.org/airblade/paper_trail) [![Dependency Status](https://img.shields.io/gemnasium/airblade/paper_trail.svg)](https://gemnasium.com/airblade/paper_trail)
2009-05-27 11:21:20 -04:00
2009-06-23 05:59:32 -04:00
PaperTrail lets you track changes to your models' data. It's good for auditing or versioning. You can see how a model looked at any stage in its lifecycle, revert it to any version, and even undelete it after it's been destroyed.
2009-05-27 11:21:20 -04:00
2013-10-02 14:54:52 -04:00
There's an excellent [RailsCast on implementing Undo with Paper Trail ](http://railscasts.com/episodes/255-undo-with-paper-trail ).
2011-07-25 16:20:52 -04:00
2009-05-27 11:21:20 -04:00
## Features
2011-08-22 04:24:04 -04:00
* Stores every create, update and destroy (or only the lifecycle events you specify).
2010-01-06 07:57:54 -05:00
* Does not store updates which don't change anything.
2011-02-25 10:29:16 -05:00
* Allows you to specify attributes (by inclusion or exclusion) which must change for a Version to be stored.
2009-05-27 11:21:20 -04:00
* Allows you to get at every version, including the original, even once destroyed.
* Allows you to get at every version even if the schema has since changed.
2010-02-18 12:34:10 -05:00
* Allows you to get at the version as of a particular time.
2014-12-16 23:47:18 -05:00
* Option to automatically restore `has_one` , `has_many` and `has_many :through` associations as they were at the time.
2010-03-19 14:53:49 -04:00
* Automatically records who was responsible via your controller. PaperTrail calls `current_user` by default, if it exists, but you can have it call any method you like.
2009-05-27 11:21:20 -04:00
* Allows you to set who is responsible at model-level (useful for migrations).
2010-03-19 14:53:49 -04:00
* Allows you to store arbitrary model-level metadata with each version (useful for filtering versions).
* Allows you to store arbitrary controller-level information with each version, e.g. remote IP.
2010-03-19 11:21:07 -04:00
* Can be turned off/on per class (useful for migrations).
2011-04-05 04:08:54 -04:00
* Can be turned off/on per request (useful for testing with an external service).
2010-03-19 11:21:07 -04:00
* Can be turned off/on globally (useful for testing).
2009-05-27 11:21:20 -04:00
* No configuration necessary.
2011-03-31 12:00:53 -04:00
* Stores everything in a single database table by default (generates migration for you), or can use separate tables for separate models.
* Supports custom version classes so different models' versions can have different behaviour.
2011-07-23 12:04:40 -04:00
* Supports custom name for versions association.
2009-05-27 11:21:20 -04:00
* Thoroughly tested.
2010-03-19 10:19:01 -04:00
* Threadsafe.
2009-05-27 11:21:20 -04:00
2013-08-07 10:51:41 -04:00
## Compatibility
2009-05-27 11:21:20 -04:00
2014-12-29 15:03:40 -05:00
Works with `ActiveRecord` 3+. Note: this code is on the `master` branch and tagged `v4.x` .
2013-08-07 10:51:41 -04:00
2014-12-30 16:44:32 -05:00
Version 3 is on the branch named [`3.0-stable` ](https://github.com/airblade/paper_trail/tree/3.0-stable ) and is tagged `v3.x` , and works ActiveRecord 4 and ActiveRecord 3.
2013-08-07 10:51:41 -04:00
Version 2 is on the branch named [`2.7-stable` ](https://github.com/airblade/paper_trail/tree/2.7-stable ) and is tagged `v2.x` , and works with Rails 3.
2013-12-11 17:45:50 -05:00
2013-08-14 16:59:52 -04:00
The Rails 2.3 code is on the [`rails2` ](https://github.com/airblade/paper_trail/tree/rails2 ) branch and tagged `v1.x` . These branches are both stable with their respective versions of Rails but will not have new features added/backported to them.
2013-08-07 10:51:41 -04:00
## Installation
### Rails 3 & 4
2014-05-19 22:25:02 -04:00
1. Add PaperTrail to your `Gemfile` .
2013-08-07 10:51:41 -04:00
2015-01-30 17:22:03 -05:00
`gem 'paper_trail', '~> 4.0.0.beta'`
2013-08-07 10:51:41 -04:00
2. Generate a migration which will add a `versions` table to your database.
`bundle exec rails generate paper_trail:install`
3. Run the migration.
`bundle exec rake db:migrate`
4. Add `has_paper_trail` to the models you want to track.
2009-05-27 11:21:20 -04:00
2013-08-13 17:10:41 -04:00
### Sinatra
2014-05-19 22:25:02 -04:00
In order to configure PaperTrail for usage with [Sinatra ](http://www.sinatrarb.com ),
your `Sinatra` app must be using `ActiveRecord` 3 or 4. It is also recommended to use the
2013-12-11 17:45:50 -05:00
[Sinatra ActiveRecord Extension ](https://github.com/janko-m/sinatra-activerecord ) or something similar for managing
your applications `ActiveRecord` connection in a manner similar to the way `Rails` does. If using the aforementioned
2014-05-19 22:25:02 -04:00
`Sinatra ActiveRecord Extension` , steps for setting up your app with PaperTrail will look something like this:
2013-09-23 17:35:17 -04:00
2014-05-19 22:25:02 -04:00
1. Add PaperTrail to your `Gemfile` .
2013-09-23 17:35:17 -04:00
2015-02-03 16:47:33 -05:00
`gem 'paper_trail', '~> 4.0.0.beta'`
2013-09-23 17:35:17 -04:00
2. Generate a migration to add a `versions` table to your database.
`bundle exec rake db:create_migration NAME=create_versions`
3. Copy contents of [create_versions.rb ](https://raw.github.com/airblade/paper_trail/master/lib/generators/paper_trail/templates/create_versions.rb )
into the `create_versions` migration that was generated into your `db/migrate` directory.
4. Run the migration.
`bundle exec rake db:migrate`
5. Add `has_paper_trail` to the models you want to track.
2013-08-13 17:10:41 -04:00
PaperTrail provides a helper extension that acts similar to the controller mixin it provides for `Rails` applications.
It will set `PaperTrail.whodunnit` to whatever is returned by a method named `user_for_paper_trail` which you can define inside your Sinatra Application. (by default it attempts to invoke a method named `current_user` )
2013-12-11 17:45:50 -05:00
If you're using the modular [`Sinatra::Base` ](http://www.sinatrarb.com/intro.html#Modular%20vs.%20Classic%20Style ) style of application, you will need to register the extension:
2013-08-13 17:10:41 -04:00
```ruby
# bleh_app.rb
require 'sinatra/base'
class BlehApp < Sinatra::Base
2013-09-26 10:29:53 -04:00
register PaperTrail::Sinatra
2013-08-13 17:10:41 -04:00
end
```
2009-05-27 11:21:20 -04:00
2010-10-28 06:14:35 -04:00
## API Summary
When you declare `has_paper_trail` in your model, you get these methods:
2011-12-10 07:09:18 -05:00
```ruby
class Widget < ActiveRecord::Base
has_paper_trail # you can pass various options here
end
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Returns this widget's versions. You can customise the name of the association.
widget.versions
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Return the version this widget was reified from, or nil if it is live.
# You can customise the name of the method.
widget.version
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Returns true if this widget is the current, live one; or false if it is from a previous version.
widget.live?
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Returns who put the widget into its current state.
widget.originator
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Returns the widget (not a version) as it looked at the given timestamp.
widget.version_at(timestamp)
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Returns the widget (not a version) as it was most recently.
widget.previous_version
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Returns the widget (not a version) as it became next.
widget.next_version
2010-10-28 06:14:35 -04:00
2014-02-21 18:20:40 -05:00
# Generates a version for a `touch` event (`widget.touch` does NOT generate a version)
widget.touch_with_version
2011-12-10 07:09:18 -05:00
# Turn PaperTrail off for all widgets.
2014-02-12 18:27:10 -05:00
Widget.paper_trail_off!
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Turn PaperTrail on for all widgets.
2014-02-12 18:27:10 -05:00
Widget.paper_trail_on!
2014-02-21 18:20:40 -05:00
2014-09-21 10:29:14 -04:00
# Check whether PaperTrail is enabled for all widgets.
2014-02-21 18:20:40 -05:00
Widget.paper_trail_enabled_for_model?
2015-01-16 13:22:12 -05:00
widget.paper_trail_enabled_for_model? # only available on instances of versioned models
2011-12-10 07:09:18 -05:00
```
2010-10-28 06:14:35 -04:00
2013-05-29 17:19:05 -04:00
And a `PaperTrail::Version` instance has these methods:
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
```ruby
# Returns the item restored from this version.
version.reify(options = {})
2010-10-28 06:14:35 -04:00
2014-07-18 04:47:21 -04:00
# Return a new item from this version
version.reify(dup: true)
2011-12-10 07:09:18 -05:00
# Returns who put the item into the state stored in this version.
version.originator
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Returns who changed the item from the state it had in this version.
version.terminator
version.whodunnit
2013-10-16 11:41:13 -04:00
version.version_author
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Returns the next version.
version.next
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Returns the previous version.
version.previous
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Returns the index of this version in all the versions.
version.index
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Returns the event that caused this version (create|update|destroy).
version.event
2014-09-21 10:29:14 -04:00
# Query versions objects by attributes.
PaperTrail::Version.where_object(attr1: val1, attr2: val2)
2015-01-07 16:57:45 -05:00
2015-01-15 11:39:48 -05:00
# Query versions object_changes field by attributes (requires
# `object_changes` column on versions table).
2015-01-16 13:01:51 -05:00
# Also can't guarantee consistent query results for numeric values
2015-01-15 11:39:48 -05:00
# due to limitations of SQL wildcard matchers against the serialized objects.
2015-01-07 16:57:45 -05:00
PaperTrail::Version.where_object_changes(attr1: val1)
2011-12-10 07:09:18 -05:00
```
2010-10-28 06:14:35 -04:00
In your controllers you can override these methods:
2011-12-10 07:09:18 -05:00
```ruby
# Returns the user who is responsible for any changes that occur.
# Defaults to current_user.
user_for_paper_trail
2010-10-28 06:14:35 -04:00
2011-12-10 07:09:18 -05:00
# Returns any information about the controller or request that you want
# PaperTrail to store alongside any changes that occur.
info_for_paper_trail
```
2010-10-28 06:14:35 -04:00
2009-05-27 11:21:20 -04:00
## Basic Usage
2009-06-23 05:39:16 -04:00
PaperTrail is simple to use. Just add 15 characters to a model to get a paper trail of every `create` , `update` , and `destroy` .
2009-05-27 11:21:20 -04:00
2011-12-10 07:09:18 -05:00
```ruby
class Widget < ActiveRecord::Base
has_paper_trail
end
```
2009-05-27 11:21:20 -04:00
This gives you a `versions` method which returns the paper trail of changes to your model.
2011-12-10 07:09:18 -05:00
```ruby
>> widget = Widget.find 42
2013-05-29 17:19:05 -04:00
>> widget.versions # [< PaperTrail::Version > , < PaperTrail::Version > , ...]
2011-12-10 07:09:18 -05:00
```
2009-05-27 11:21:20 -04:00
Once you have a version, you can find out what happened:
2011-12-10 07:09:18 -05:00
```ruby
>> v = widget.versions.last
>> v.event # 'update' (or 'create' or 'destroy')
>> v.whodunnit # '153' (if the update was via a controller and
# the controller has a current_user method,
# here returning the id of the current user)
>> v.created_at # when the update occurred
>> widget = v.reify # the widget as it was before the update;
# would be nil for a create event
```
2009-05-27 11:21:20 -04:00
2009-06-23 05:39:16 -04:00
PaperTrail stores the pre-change version of the model, unlike some other auditing/versioning plugins, so you can retrieve the original version. This is useful when you start keeping a paper trail for models that already have records in the database.
2009-05-27 11:21:20 -04:00
2011-12-10 07:09:18 -05:00
```ruby
>> widget = Widget.find 153
>> widget.name # 'Doobly'
2009-06-23 05:39:16 -04:00
2011-12-10 07:09:18 -05:00
# Add has_paper_trail to Widget model.
2009-06-23 05:39:16 -04:00
2011-12-10 07:09:18 -05:00
>> widget.versions # []
>> widget.update_attributes :name => 'Wotsit'
2013-08-28 02:45:14 -04:00
>> widget.versions.last.reify.name # 'Doobly'
2012-10-12 19:05:27 -04:00
>> widget.versions.last.event # 'update'
2011-12-10 07:09:18 -05:00
```
2009-05-27 11:21:20 -04:00
2009-06-23 05:39:16 -04:00
This also means that PaperTrail does not waste space storing a version of the object as it currently stands. The `versions` method gives you previous versions; to get the current one just call a finder on your `Widget` model as usual.
2009-05-27 11:21:20 -04:00
Here's a helpful table showing what PaperTrail stores:
< table >
< tr >
< th > Event< / th >
< th > Model Before< / th >
< th > Model After< / th >
< / tr >
< tr >
< td > create< / td >
< td > nil< / td >
< td > widget< / td >
< / tr >
< tr >
< td > update< / td >
< td > widget< / td >
2014-10-28 08:58:34 -04:00
< td > widget< / td >
2009-05-27 11:21:20 -04:00
< tr >
< td > destroy< / td >
< td > widget< / td >
< td > nil< / td >
2014-01-02 09:59:32 -05:00
< / tr >
2009-05-27 11:21:20 -04:00
< / table >
2009-06-23 05:39:16 -04:00
PaperTrail stores the values in the Model Before column. Most other auditing/versioning plugins store the After column.
2011-08-22 04:24:04 -04:00
## Choosing Lifecycle Events To Monitor
You can choose which events to track with the `on` option. For example, to ignore `create` events:
2011-12-10 07:09:18 -05:00
```ruby
class Article < ActiveRecord::Base
has_paper_trail :on => [:update, :destroy]
end
```
2011-08-22 04:24:04 -04:00
2013-05-29 17:19:05 -04:00
You may also have the `PaperTrail::Version` model save a custom string in it's `event` field instead of the typical `create` , `update` , `destroy` .
2013-05-13 11:38:53 -04:00
PaperTrail supplies a custom accessor method called `paper_trail_event` , which it will attempt to use to fill the `event` field before
falling back on one of the default events.
```ruby
>> a = Article.create
>> a.versions.size # 1
>> a.versions.last.event # 'create'
>> a.paper_trail_event = 'update title'
>> a.update_attributes :title => 'My Title'
>> a.versions.size # 2
>> a.versions.last.event # 'update title'
>> a.paper_trail_event = nil
>> a.update_attributes :title => "Alternate"
>> a.versions.size # 3
>> a.versions.last.event # 'update'
```
2011-08-22 04:24:04 -04:00
2012-01-17 11:35:24 -05:00
## Choosing When To Save New Versions
2012-01-11 09:26:10 -05:00
2012-01-17 11:35:24 -05:00
You can choose the conditions when to add new versions with the `if` and `unless` options. For example, to save versions only for US non-draft translations:
2012-01-11 09:26:10 -05:00
2012-10-12 19:05:27 -04:00
```ruby
class Translation < ActiveRecord::Base
has_paper_trail :if => Proc.new { |t| t.language_code == 'US' },
:unless => Proc.new { |t| t.type == 'DRAFT' }
end
```
2012-01-11 09:26:10 -05:00
2011-08-22 04:24:04 -04:00
2011-02-25 09:36:32 -05:00
## Choosing Attributes To Monitor
2009-10-28 09:12:36 -04:00
You can ignore changes to certain attributes like this:
2011-12-10 07:09:18 -05:00
```ruby
class Article < ActiveRecord::Base
2013-09-19 16:18:02 -04:00
has_paper_trail :ignore => [:title, :rating]
2011-12-10 07:09:18 -05:00
end
```
2009-10-28 09:12:36 -04:00
2013-05-29 17:19:05 -04:00
This means that changes to just the `title` or `rating` will not store another version of the article. It does not mean that the `title` and `rating` attributes will be ignored if some other change causes a new `PaperTrail::Version` to be created. For example:
2009-10-28 09:12:36 -04:00
2011-12-10 07:09:18 -05:00
```ruby
>> a = Article.create
>> a.versions.length # 1
2013-09-19 07:34:13 -04:00
>> a.update_attributes :title => 'My Title', :rating => 3
2013-09-19 16:18:02 -04:00
>> a.versions.length # 1
2013-09-19 07:34:13 -04:00
>> a.update_attributes :title => 'Greeting', :content => 'Hello'
2013-09-19 16:18:02 -04:00
>> a.versions.length # 2
2012-10-12 19:05:27 -04:00
>> a.previous_version.title # 'My Title'
2011-12-10 07:09:18 -05:00
```
2009-10-28 09:12:36 -04:00
2011-02-25 09:36:32 -05:00
Or, you can specify a list of all attributes you care about:
2011-12-10 07:09:18 -05:00
```ruby
class Article < ActiveRecord::Base
2013-09-19 16:18:02 -04:00
has_paper_trail :only => [:title]
2011-12-10 07:09:18 -05:00
end
```
2011-02-25 09:36:32 -05:00
2013-09-19 16:18:02 -04:00
This means that only changes to the `title` will save a version of the article:
2011-02-25 09:36:32 -05:00
2011-12-10 07:09:18 -05:00
```ruby
>> a = Article.create
>> a.versions.length # 1
>> a.update_attributes :title => 'My Title'
>> a.versions.length # 2
>> a.update_attributes :content => 'Hello'
>> a.versions.length # 2
2012-10-12 19:32:27 -04:00
>> a.previous_version.content # nil
2013-09-19 16:18:02 -04:00
```
The `:ignore` and `:only` options can also accept `Hash` arguments, where the :
```ruby
class Article < ActiveRecord::Base
has_paper_trail :only => [:title => Proc.new { |obj| !obj.title.blank? } ]
end
```
This means that if the `title` is not blank, then only changes to the `title` will save a version of the article:
```ruby
>> a = Article.create
>> a.versions.length # 1
>> a.update_attributes :content => 'Hello'
>> a.versions.length # 2
>> a.update_attributes :title => 'My Title'
2013-09-19 07:34:13 -04:00
>> a.versions.length # 3
2013-09-19 16:18:02 -04:00
>> a.update_attributes :content => 'Hai'
2013-09-19 07:34:13 -04:00
>> a.versions.length # 3
2013-09-19 16:18:02 -04:00
>> a.previous_version.content # "Hello"
>> a.update_attributes :title => 'Dif Title'
>> a.versions.length # 4
>> a.previous_version.content # "Hai"
2011-12-10 07:09:18 -05:00
```
2011-02-25 10:26:41 -05:00
2011-02-25 09:36:32 -05:00
Passing both `:ignore` and `:only` options will result in the article being saved if a changed attribute is included in `:only` but not in `:ignore` .
2009-10-28 09:12:36 -04:00
2013-05-29 17:19:05 -04:00
You can skip fields altogether with the `:skip` option. As with `:ignore` , updates to these fields will not create a new `PaperTrail::Version` . In addition, these fields will not be included in the serialized version of the object whenever a new `PaperTrail::Version` is created.
2011-11-09 05:06:17 -05:00
For example:
2011-12-10 07:09:18 -05:00
```ruby
class Article < ActiveRecord::Base
has_paper_trail :skip => [:file_upload]
end
```
2011-02-25 10:26:41 -05:00
2009-06-23 05:59:32 -04:00
## Reverting And Undeleting A Model
2009-06-23 05:39:16 -04:00
2009-06-23 05:59:32 -04:00
PaperTrail makes reverting to a previous version easy:
2009-06-23 05:39:16 -04:00
2011-12-10 07:09:18 -05:00
```ruby
>> widget = Widget.find 42
>> widget.update_attributes :name => 'Blah blah'
# Time passes....
2011-12-10 07:50:48 -05:00
>> widget = widget.previous_version # the widget as it was before the update
2012-10-12 19:05:27 -04:00
>> widget.save # reverted
2011-12-10 07:09:18 -05:00
```
2009-06-23 05:59:32 -04:00
2010-02-18 12:34:10 -05:00
Alternatively you can find the version at a given time:
2011-12-10 07:09:18 -05:00
```ruby
>> widget = widget.version_at(1.day.ago) # the widget as it was one day ago
>> widget.save # reverted
```
2010-02-18 12:34:10 -05:00
Note `version_at` gives you the object, not a version, so you don't need to call `reify` .
2009-06-23 05:59:32 -04:00
Undeleting is just as simple:
2009-06-23 05:39:16 -04:00
2011-12-10 07:09:18 -05:00
```ruby
>> widget = Widget.find 42
>> widget.destroy
# Time passes....
2013-10-28 12:30:47 -04:00
>> widget = PaperTrail::Version.find(153).reify # the widget as it was before destruction
2011-12-10 07:09:18 -05:00
>> widget.save # the widget lives!
```
2009-06-23 05:39:16 -04:00
2011-03-01 05:50:35 -05:00
In fact you could use PaperTrail to implement an undo system, though I haven't had the opportunity yet to do it myself. However [Ryan Bates has ](http://railscasts.com/episodes/255-undo-with-paper-trail )!
2009-05-27 11:21:20 -04:00
2010-06-22 07:48:36 -04:00
## Navigating Versions
2010-06-22 09:41:26 -04:00
You can call `previous_version` and `next_version` on an item to get it as it was/became. Note that these methods reify the item for you.
2011-12-10 07:09:18 -05:00
```ruby
2012-10-16 22:28:48 -04:00
>> live_widget = Widget.find 42
2013-10-28 12:30:47 -04:00
>> live_widget.versions.length # 4 for example
>> widget = live_widget.previous_version # => widget == live_widget.versions.last.reify
>> widget = widget.previous_version # => widget == live_widget.versions[-2].reify
>> widget = widget.next_version # => widget == live_widget.versions.last.reify
2014-02-06 09:27:57 -05:00
>> widget.next_version # live_widget
2011-12-10 07:09:18 -05:00
```
2010-06-22 09:41:26 -04:00
If instead you have a particular `version` of an item you can navigate to the previous and next versions.
2010-06-22 07:48:36 -04:00
2011-12-10 07:09:18 -05:00
```ruby
>> widget = Widget.find 42
>> version = widget.versions[-2] # assuming widget has several versions
>> previous = version.previous
>> next = version.next
```
2010-06-22 07:48:36 -04:00
You can find out which of an item's versions yours is:
2011-12-10 07:09:18 -05:00
```ruby
>> current_version_number = version.index # 0-based
```
2010-06-22 07:48:36 -04:00
2014-09-21 10:29:14 -04:00
If you got an item by reifying one of its versions, you can navigate back to the version it came from:
2010-06-22 07:48:36 -04:00
2011-12-10 07:09:18 -05:00
```ruby
>> latest_version = Widget.find(42).versions.last
>> widget = latest_version.reify
>> widget.version == latest_version # true
```
2010-06-22 07:48:36 -04:00
2010-10-21 07:30:50 -04:00
You can find out whether a model instance is the current, live one -- or whether it came instead from a previous version -- with `live?` :
2011-12-10 07:09:18 -05:00
```ruby
>> widget = Widget.find 42
>> widget.live? # true
2011-12-10 07:50:48 -05:00
>> widget = widget.previous_version
2011-12-10 07:09:18 -05:00
>> widget.live? # false
```
2010-06-22 07:48:36 -04:00
2014-09-21 10:29:14 -04:00
And you can perform `WHERE` queries for object versions based on attributes:
```ruby
>> # All versions that meet these criteria.
>> PaperTrail::Version.where_object(content: "Hello", title: "Article")
```
2009-05-27 11:21:20 -04:00
## Finding Out Who Was Responsible For A Change
2013-12-11 17:45:50 -05:00
If your `ApplicationController` has a `current_user` method, PaperTrail will store the value it returns in the version's `whodunnit` column. Note that this column is of type `String` , so you will have to convert it to an integer if it's an id and you want to look up the user later on:
2009-05-27 11:21:20 -04:00
2011-12-10 07:09:18 -05:00
```ruby
2013-07-10 10:37:35 -04:00
>> last_change = widget.versions.last
2011-12-10 07:09:18 -05:00
>> user_who_made_the_change = User.find last_change.whodunnit.to_i
```
2009-05-27 11:21:20 -04:00
2010-03-19 14:53:49 -04:00
You may want PaperTrail to call a different method to find out who is responsible. To do so, override the `user_for_paper_trail` method in your controller like this:
2011-12-10 07:09:18 -05:00
```ruby
class ApplicationController
def user_for_paper_trail
2014-02-12 16:27:17 -05:00
logged_in? ? current_member.id : 'Public user' # or whatever
2011-12-10 07:09:18 -05:00
end
end
```
2010-03-19 14:53:49 -04:00
2013-12-11 17:45:50 -05:00
In a console session you can manually set who is responsible like this:
2009-05-27 11:21:20 -04:00
2011-12-10 07:09:18 -05:00
```ruby
>> PaperTrail.whodunnit = 'Andy Stewart'
>> widget.update_attributes :name => 'Wibble'
>> widget.versions.last.whodunnit # Andy Stewart
```
2009-05-27 11:21:20 -04:00
2012-11-06 10:15:12 -05:00
You can avoid having to do this manually by setting your initializer to pick up the username of the current user from the OS, like this:
```ruby
2014-03-11 17:55:44 -04:00
# config/initializers/paper_trail.rb
2014-07-22 19:40:11 -04:00
2014-12-29 15:03:40 -05:00
# the following line is required for PaperTrail >= 4.0.0 with Rails
2014-07-22 19:40:11 -04:00
PaperTrail::Rails::Engine.eager_load!
2014-03-12 09:53:17 -04:00
if defined?(::Rails::Console)
PaperTrail.whodunnit = "#{`whoami`.strip}: console"
elsif File.basename($0) == "rake"
PaperTrail.whodunnit = "#{`whoami`.strip}: rake #{ARGV.join ' '}"
2012-11-06 10:15:12 -05:00
end
```
2009-05-27 11:21:20 -04:00
2014-03-11 17:55:44 -04:00
Sometimes you want to define who is responsible for a change in a small scope without overwriting value of `PaperTrail.whodunnit` . It is possible to define the `whodunnit` value for an operation inside a block like this:
```ruby
>> PaperTrail.whodunnit = 'Andy Stewart'
>> widget.whodunnit('Lucas Souza') do
>> widget.update_attributes :name => 'Wibble'
>> end
>> widget.versions.last.whodunnit # Lucas Souza
>> widget.update_attributes :name => 'Clair'
>> widget.versions.last.whodunnit # Andy Stewart
>> widget.whodunnit('Ben Atkins') { |w| w.update_attributes :name => 'Beth' } # this syntax also works
>> widget.versions.last.whodunnit # Ben Atkins
```
2013-12-11 17:45:50 -05:00
A version's `whodunnit` records who changed the object causing the `version` to be stored. Because a version stores the object as it looked before the change (see the table above), `whodunnit` returns who stopped the object looking like this -- not who made it look like this. Hence `whodunnit` is aliased as `terminator` .
2010-06-28 09:03:35 -04:00
2013-12-11 17:45:50 -05:00
To find out who made a version's object look that way, use `version.originator` . And to find out who made a "live" object look like it does, use `originator` on the object.
2010-06-28 09:03:35 -04:00
2011-12-10 07:09:18 -05:00
```ruby
>> widget = Widget.find 153 # assume widget has 0 versions
>> PaperTrail.whodunnit = 'Alice'
>> widget.update_attributes :name => 'Yankee'
>> widget.originator # 'Alice'
>> PaperTrail.whodunnit = 'Bob'
>> widget.update_attributes :name => 'Zulu'
>> widget.originator # 'Bob'
>> first_version, last_version = widget.versions.first, widget.versions.last
>> first_version.whodunnit # 'Alice'
>> first_version.originator # nil
>> first_version.terminator # 'Alice'
>> last_version.whodunnit # 'Bob'
>> last_version.originator # 'Alice'
>> last_version.terminator # 'Bob'
```
2009-05-27 11:21:20 -04:00
2011-03-31 12:00:53 -04:00
## Custom Version Classes
You can specify custom version subclasses with the `:class_name` option:
2011-12-10 07:09:18 -05:00
```ruby
2013-05-29 17:19:05 -04:00
class PostVersion < PaperTrail::Version
2011-12-10 07:09:18 -05:00
# custom behaviour, e.g:
2012-10-12 19:05:27 -04:00
self.table_name = :post_versions
2011-12-10 07:09:18 -05:00
end
2011-03-31 12:00:53 -04:00
2011-12-10 07:09:18 -05:00
class Post < ActiveRecord::Base
has_paper_trail :class_name => 'PostVersion'
end
```
2011-11-06 18:12:03 -05:00
2011-03-31 12:00:53 -04:00
This allows you to store each model's versions in a separate table, which is useful if you have a lot of versions being created.
2012-04-13 01:36:31 -04:00
If you are using Postgres, you should also define the sequence that your custom version class will use:
2012-10-12 19:05:27 -04:00
```ruby
2013-05-29 17:19:05 -04:00
class PostVersion < PaperTrail::Version
2012-10-12 19:05:27 -04:00
self.table_name = :post_versions
2015-01-29 19:34:38 -05:00
self.sequence_name = :post_versions_id_seq
2012-10-12 19:05:27 -04:00
end
```
2012-04-13 01:36:31 -04:00
2011-03-31 12:00:53 -04:00
Alternatively you could store certain metadata for one type of version, and other metadata for other versions.
2013-12-11 17:45:50 -05:00
If you only use custom version classes and don't use PaperTrail's built-in one, on Rails `>= 3.2` you must:
2012-02-08 08:49:42 -05:00
2014-03-12 15:02:34 -04:00
- either declare the `PaperTrail::Version` class to be abstract like this (in an initializer):
2012-02-08 08:49:42 -05:00
2012-10-12 19:05:27 -04:00
```ruby
2014-07-22 19:40:11 -04:00
# config/initializers/paper_trail.rb
2014-12-29 15:03:40 -05:00
# the following line is required for PaperTrail >= 4.0.0 with Rails
2014-07-22 19:40:11 -04:00
PaperTrail::Rails::Engine.eager_load!
2013-05-29 17:19:05 -04:00
PaperTrail::Version.module_eval do
2012-10-12 19:05:27 -04:00
self.abstract_class = true
end
```
2012-02-08 08:49:42 -05:00
2013-12-11 17:45:50 -05:00
- or create a `versions` table in the database so Rails can instantiate the `PaperTrail::Version` superclass.
2012-02-08 08:49:42 -05:00
2011-11-11 08:29:19 -05:00
You can also specify custom names for the versions and version associations. This is useful if you already have `versions` or/and `version` methods on your model. For example:
2011-07-23 12:04:40 -04:00
2011-12-10 07:09:18 -05:00
```ruby
class Post < ActiveRecord::Base
has_paper_trail :versions => :paper_trail_versions,
:version => :paper_trail_version
# Existing versions method. We don't want to clash.
def versions
...
end
# Existing version method. We don't want to clash.
def version
...
end
end
```
2011-03-31 12:00:53 -04:00
2011-03-01 05:58:22 -05:00
## Associations
2014-12-24 12:13:13 -05:00
PaperTrail can restore three types of associations: Has-One, Has-Many, and Has-Many-Through. In order to do this, you will need to create a `version_associations` table, either at installation time with the `rails generate paper_trail:install --with-associations` option or manually. PaperTrail will store in that table additional information to correlate versions of the association and versions of the model when the associated record is changed. When reifying the model, PaperTrail can use this table, together with the `transaction_id` to find the correct version of the association and reify it. The `transaction_id` is a unique id for version records created in the same transaction. It is used to associate the version of the model and the version of the association that are created in the same transaction.
2011-03-01 05:58:22 -05:00
2014-12-16 23:47:18 -05:00
To restore Has-One associations as they were at the time, pass option `:has_one => true` to `reify` . To restore Has-Many and Has-Many-Through associations, use option `:has_many => true` . For example:
2010-10-20 08:48:52 -04:00
2011-12-10 07:09:18 -05:00
```ruby
2014-03-12 05:03:32 -04:00
class Location < ActiveRecord::Base
belongs_to :treasure
has_paper_trail
end
2011-12-10 07:09:18 -05:00
class Treasure < ActiveRecord::Base
has_one :location
2014-03-12 05:03:32 -04:00
has_paper_trail
2011-12-10 07:09:18 -05:00
end
2010-10-20 08:48:52 -04:00
2011-12-10 07:09:18 -05:00
>> treasure.amount # 100
>> treasure.location.latitude # 12.345
2010-10-20 08:48:52 -04:00
2011-12-10 07:09:18 -05:00
>> treasure.update_attributes :amount => 153
>> treasure.location.update_attributes :latitude => 54.321
2011-07-14 05:25:10 -04:00
2011-12-10 07:09:18 -05:00
>> t = treasure.versions.last.reify(:has_one => true)
>> t.amount # 100
>> t.location.latitude # 12.345
```
2010-10-20 09:26:44 -04:00
2014-12-16 23:47:18 -05:00
If the parent and child are updated in one go, PaperTrail can use the aforementioned `transaction_id` to reify the models as they were before the transaction (instead of before the update to the model).
2010-10-21 09:04:28 -04:00
2011-12-10 07:09:18 -05:00
```ruby
2014-12-16 23:47:18 -05:00
>> treasure.amount # 100
>> treasure.location.latitude # 12.345
>> Treasure.transaction do
>> treasure.location.update_attributes :latitude => 54.321
>> treasure.update_attributes :amount => 153
>> end
>> t = treasure.versions.last.reify(:has_one => true)
>> t.amount # 100
>> t.location.latitude # 12.345, instead of 54.321
2011-12-10 07:09:18 -05:00
```
2010-10-21 09:04:28 -04:00
2014-12-16 23:47:18 -05:00
By default, PaperTrail excludes an associated record from the reified parent model if the associated record exists in the live model but did not exist as at the time the version was created. This is usually what you want if you just want to look at the reified version. But if you want to persist it, it would be better to pass in option `:mark_for_destruction => true` so that the associated record is included and marked for destruction.
2010-10-21 09:04:28 -04:00
2014-12-16 23:47:18 -05:00
```ruby
class Widget < ActiveRecord::Base
has_paper_trail
has_one :wotsit, autosave: true
end
2010-10-20 08:48:52 -04:00
2014-12-16 23:47:18 -05:00
class Wotsit < ActiveRecord::Base
has_paper_trail
belongs_to :widget
end
>> widget = Widget.create(:name => 'widget_0')
>> widget.update_attributes(:name => 'widget_1')
>> widget.create_wotsit(:name => 'wotsit')
2010-10-20 08:48:52 -04:00
2014-12-16 23:47:18 -05:00
>> widget_0 = widget.versions.last.reify(:has_one => true)
>> widget_0.wotsit # nil
>> widget_0 = widget.versions.last.reify(:has_one => true, :mark_for_destruction => true)
>> widget_0.wotsit.marked_for_destruction? # true
>> widget_0.save!
>> widget.reload.wotsit # nil
```
**Caveats:**
1. PaperTrail can't restore an association properly if the association record can be updated to replace its parent model (by replacing the foreign key)
2. Currently PaperTrail only support single `version_associations` table. The implication is that you can only use a single table to store the versions for all related models. Sorry for those who use multiple version tables.
3. PaperTrail only reifies the first level of associations, i.e., it does not reify any associations of its associations, and so on.
4. PaperTrail relies on the callbacks on the association model (and the :through association model for Has-Many-Through associations) to record the versions and the relationship between the versions. If the association is changed without invoking the callbacks, Reification won't work. Below are some examples:
2010-07-05 08:01:02 -04:00
Given these models:
2011-12-10 07:09:18 -05:00
```ruby
class Book < ActiveRecord::Base
has_many :authorships, :dependent => :destroy
has_many :authors, :through => :authorships, :source => :person
has_paper_trail
end
class Authorship < ActiveRecord::Base
belongs_to :book
belongs_to :person
has_paper_trail # NOTE
end
class Person < ActiveRecord::Base
has_many :authorships, :dependent => :destroy
has_many :books, :through => :authorships
has_paper_trail
end
```
2010-07-05 08:01:02 -04:00
Then each of the following will store authorship versions:
2011-12-10 07:09:18 -05:00
```ruby
>> @book .authors << @dostoyevsky
>> @book .authors.create :name => 'Tolstoy'
>> @book .authorships.last.destroy
>> @book .authorships.clear
2014-12-16 23:47:18 -05:00
>> @book .author_ids = [@solzhenistyn.id, @dostoyevsky .id]
2011-12-10 07:09:18 -05:00
```
2010-07-05 08:01:02 -04:00
But none of these will:
2011-12-10 07:09:18 -05:00
```ruby
>> @book .authors.delete @tolstoy
2014-12-16 23:47:18 -05:00
>> @book .author_ids = []
2011-12-10 07:09:18 -05:00
>> @book .authors = []
```
2010-07-05 08:01:02 -04:00
2011-11-25 02:54:22 -05:00
Having said that, you can apparently get all these working (I haven't tested it myself) with this patch:
2011-12-10 07:09:18 -05:00
```ruby
# In config/initializers/active_record_patch.rb
module ActiveRecord
# = Active Record Has Many Through Association
module Associations
class HasManyThroughAssociation < HasManyAssociation #:nodoc:
alias_method :original_delete_records, :delete_records
def delete_records(records, method)
method ||= :destroy
original_delete_records(records, method)
2010-10-28 05:41:25 -04:00
end
end
2011-12-10 07:09:18 -05:00
end
end
```
2010-10-28 05:41:25 -04:00
2011-11-25 02:54:22 -05:00
See [issue 113 ](https://github.com/airblade/paper_trail/issues/113 ) for a discussion about this.
2010-09-03 05:06:41 -04:00
2010-07-05 08:01:02 -04:00
2010-01-06 07:57:54 -05:00
## Storing metadata
2010-03-19 14:53:49 -04:00
You can store arbitrary model-level metadata alongside each version like this:
2010-01-06 07:57:54 -05:00
2011-12-10 07:09:18 -05:00
```ruby
class Article < ActiveRecord::Base
belongs_to :author
2012-11-27 13:15:59 -05:00
has_paper_trail :meta => { :author_id => :author_id,
2011-12-10 07:09:18 -05:00
:word_count => :count_words,
:answer => 42 }
def count_words
153
end
end
```
2010-01-06 07:57:54 -05:00
2011-09-29 05:00:13 -04:00
PaperTrail will call your proc with the current article and store the result in the `author_id` column of the `versions` table.
N.B. You must also:
* Add your metadata columns to the `versions` table.
2014-03-12 09:40:20 -04:00
* Declare your metadata columns using `attr_accessible` . (If you are using `ActiveRecord 3` , or `ActiveRecord 4` with the [ProtectedAttributes ](https://github.com/rails/protected_attributes ) gem)
2011-11-09 04:50:55 -05:00
For example:
2011-09-29 05:00:13 -04:00
2011-12-10 07:09:18 -05:00
```ruby
# config/initializers/paper_trail.rb
2014-07-08 18:54:27 -04:00
2014-12-29 15:03:40 -05:00
# the following line is required for PaperTrail >= 4.0.0 with Rails
2014-07-08 18:54:27 -04:00
PaperTrail::Rails::Engine.eager_load!
2013-05-29 17:19:05 -04:00
module PaperTrail
class Version < ActiveRecord::Base
attr_accessible :author_id, :word_count, :answer
end
2011-12-10 07:09:18 -05:00
end
```
2010-01-06 07:57:54 -05:00
2013-10-17 22:05:24 -04:00
Why would you do this? In this example, `author_id` is an attribute of `Article` and PaperTrail will store it anyway in a serialized form in the `object` column of the `version` record. But let's say you wanted to pull out all versions for a particular author; without the metadata you would have to deserialize (reify) each `version` object to see if belonged to the author in question. Clearly this is inefficient. Using the metadata you can find just those versions you want:
2010-01-06 07:57:54 -05:00
2011-12-10 07:09:18 -05:00
```ruby
2013-11-25 11:18:40 -05:00
PaperTrail::Version.where(:author_id => author_id)
2011-12-10 07:09:18 -05:00
```
2010-01-06 07:57:54 -05:00
2011-02-08 08:07:31 -05:00
Note you can pass a symbol as a value in the `meta` hash to signal a method to call.
2010-03-19 14:53:49 -04:00
You can also store any information you like from your controller. Just override the `info_for_paper_trail` method in your controller to return a hash whose keys correspond to columns in your `versions` table. E.g.:
2011-12-10 07:09:18 -05:00
```ruby
class ApplicationController
def info_for_paper_trail
{ :ip => request.remote_ip, :user_agent => request.user_agent }
end
end
```
2010-03-19 14:53:49 -04:00
2011-09-29 05:00:13 -04:00
Remember to add those extra columns to your `versions` table and use `attr_accessible` ;)
2010-03-19 14:53:49 -04:00
2014-01-02 09:59:32 -05:00
**NOTE FOR RAILS 4:** If you're using [Strong Parameters ](https://github.com/rails/strong_parameters ) in Rails 4 and have *not* included the `protected_attributes` gem, there's no need to declare your metadata columns using `attr_accessible` .
2013-12-31 06:19:51 -05:00
2010-01-06 07:57:54 -05:00
2010-06-23 06:47:56 -04:00
## Diffing Versions
2011-07-13 05:21:49 -04:00
There are two scenarios: diffing adjacent versions and diffing non-adjacent versions.
2010-06-23 06:47:56 -04:00
2014-03-05 17:09:57 -05:00
The best way to diff adjacent versions is to get PaperTrail to do it for you. If you add an `object_changes` text column to your `versions` table, either at installation time with the `rails generate paper_trail:install --with-changes` option or manually, PaperTrail will store the `changes` diff (excluding any attributes PaperTrail is ignoring) in each `update` version. You can use the `version.changeset` method to retrieve it. For example:
2010-06-23 06:47:56 -04:00
2011-12-10 07:09:18 -05:00
```ruby
>> widget = Widget.create :name => 'Bob'
2012-10-16 16:49:48 -04:00
>> widget.versions.last.changeset # {'name' => [nil, 'Bob']}
2011-12-10 07:09:18 -05:00
>> widget.update_attributes :name => 'Robert'
>> widget.versions.last.changeset # {'name' => ['Bob', 'Robert']}
2012-10-16 16:49:48 -04:00
>> widget.destroy
>> widget.versions.last.changeset # {}
2011-12-10 07:09:18 -05:00
```
2011-07-13 05:21:49 -04:00
2012-10-16 16:49:48 -04:00
Note PaperTrail only stores the changes for creation and updates; it doesn't store anything when an object is destroyed.
2011-07-13 05:21:49 -04:00
Please be aware that PaperTrail doesn't use diffs internally. When I designed PaperTrail I wanted simplicity and robustness so I decided to make each version of an object self-contained. A version stores all of its object's data, not a diff from the previous version. This means you can delete any version without affecting any other.
To diff non-adjacent versions you'll have to write your own code. These libraries may help:
2010-06-23 06:47:56 -04:00
For diffing two strings:
* [htmldiff ](http://github.com/myobie/htmldiff ): expects but doesn't require HTML input and produces HTML output. Works very well but slows down significantly on large (e.g. 5,000 word) inputs.
* [differ ](http://github.com/pvande/differ ): expects plain text input and produces plain text/coloured/HTML/any output. Can do character-wise, word-wise, line-wise, or arbitrary-boundary-string-wise diffs. Works very well on non-HTML input.
2012-09-28 18:34:52 -04:00
* [diff-lcs ](https://github.com/halostatue/diff-lcs ): old-school, line-wise diffs.
2010-06-23 06:47:56 -04:00
For diffing two ActiveRecord objects:
* [Jeremy Weiskotten's PaperTrail fork ](http://github.com/jeremyw/paper_trail/blob/master/lib/paper_trail/has_paper_trail.rb#L151-156 ): uses ActiveSupport's diff to return an array of hashes of the changes.
* [activerecord-diff ](http://github.com/tim/activerecord-diff ): rather like ActiveRecord::Dirty but also allows you to specify which columns to compare.
2009-05-27 11:21:20 -04:00
## Turning PaperTrail Off/On
2010-03-19 11:21:07 -04:00
Sometimes you don't want to store changes. Perhaps you are only interested in changes made by your users and don't need to store changes you make yourself in, say, a migration -- or when testing your application.
2009-05-27 11:21:20 -04:00
2011-04-05 04:08:54 -04:00
You can turn PaperTrail on or off in three ways: globally, per request, or per class.
2009-05-27 11:21:20 -04:00
2011-04-05 04:08:54 -04:00
### Globally
2009-05-27 11:21:20 -04:00
2011-04-05 04:08:54 -04:00
On a global level you can turn PaperTrail off like this:
2010-03-19 11:21:07 -04:00
2011-12-10 07:09:18 -05:00
```ruby
>> PaperTrail.enabled = false
```
2010-03-19 11:21:07 -04:00
2014-02-19 16:03:13 -05:00
For example, you might want to disable PaperTrail in your Rails application's test environment to speed up your tests. This will do it (note: this gets done automatically for `RSpec` and `Cucumber` , please see the [Testing section ](#testing )):
2010-03-19 11:21:07 -04:00
2011-12-10 07:09:18 -05:00
```ruby
# in config/environments/test.rb
config.after_initialize do
PaperTrail.enabled = false
end
```
2010-03-19 11:21:07 -04:00
If you disable PaperTrail in your test environment but want to enable it for specific tests, you can add a helper like this to your test helper:
2011-12-10 07:09:18 -05:00
```ruby
# in test/test_helper.rb
def with_versioning
was_enabled = PaperTrail.enabled?
2014-08-22 11:16:38 -04:00
was_enabled_for_controller = PaperTrail.enabled_for_controller?
2011-12-10 07:09:18 -05:00
PaperTrail.enabled = true
2014-08-22 11:16:38 -04:00
PaperTrail.enabled_for_controller = true
2011-12-10 07:09:18 -05:00
begin
yield
ensure
PaperTrail.enabled = was_enabled
2014-08-22 11:16:38 -04:00
PaperTrail.enabled_for_controller = was_enabled_for_controller
2011-12-10 07:09:18 -05:00
end
end
```
2010-03-19 11:21:07 -04:00
And then use it in your tests like this:
2011-12-10 07:09:18 -05:00
```ruby
test "something that needs versioning" do
with_versioning do
# your test
end
end
```
2010-03-19 11:21:07 -04:00
2011-04-05 04:08:54 -04:00
### Per request
2013-10-10 17:46:42 -04:00
You can turn PaperTrail on or off per request by adding a `paper_trail_enabled_for_controller` method to your controller which returns `true` or `false` :
2011-04-05 04:08:54 -04:00
2011-12-10 07:09:18 -05:00
```ruby
class ApplicationController < ActionController::Base
def paper_trail_enabled_for_controller
request.user_agent != 'Disable User-Agent'
end
end
```
2011-04-05 04:08:54 -04:00
### Per class
2014-09-12 09:37:51 -04:00
If you are about to change some widgets and you don't want a paper trail of your changes, you can turn PaperTrail off like this:
2011-04-05 04:08:54 -04:00
2011-12-10 07:09:18 -05:00
```ruby
2014-02-12 18:27:10 -05:00
>> Widget.paper_trail_off!
2011-12-10 07:09:18 -05:00
```
2011-04-05 04:08:54 -04:00
And on again like this:
2011-12-10 07:09:18 -05:00
```ruby
2014-02-12 18:27:10 -05:00
>> Widget.paper_trail_on!
2011-12-10 07:09:18 -05:00
```
2011-04-05 04:08:54 -04:00
2011-08-31 05:25:52 -04:00
### Per method call
You can call a method without creating a new version using `without_versioning` . It takes either a method name as a symbol:
2011-12-10 07:09:18 -05:00
```ruby
@widget .without_versioning :destroy
```
2011-08-31 05:25:52 -04:00
Or a block:
2011-12-10 07:09:18 -05:00
```ruby
@widget .without_versioning do
@widget .update_attributes :name => 'Ford'
end
```
2009-05-27 11:21:20 -04:00
2012-07-03 23:22:52 -04:00
## Using a custom serializer
2013-10-17 22:05:24 -04:00
By default, PaperTrail stores your changes as a `YAML` dump. You can override this with the serializer config option:
2012-07-03 23:22:52 -04:00
```ruby
2013-02-15 13:04:28 -05:00
>> PaperTrail.serializer = MyCustomSerializer
2012-07-03 23:22:52 -04:00
```
2013-01-23 15:56:10 -05:00
A valid serializer is a `module` (or `class` ) that defines a `load` and `dump` method. These serializers are included in the gem for your convenience:
2013-01-22 18:13:58 -05:00
2014-09-23 17:38:14 -04:00
* [PaperTrail::Serializers::YAML ](https://github.com/airblade/paper_trail/blob/master/lib/paper_trail/serializers/yaml.rb ) - Default
* [PaperTrail::Serializers::JSON ](https://github.com/airblade/paper_trail/blob/master/lib/paper_trail/serializers/json.rb )
2012-07-03 23:22:52 -04:00
2015-01-29 17:52:56 -05:00
### PostgreSQL JSON column type support
2015-01-22 14:45:08 -05:00
If you use PostgreSQL, and would like to store your `object` (and/or `object_changes` ) data in a column of
[type `JSON` ](http://www.postgresql.org/docs/9.4/static/datatype-json.html ),
specify `json` instead of `text` for these columns in your migration:
2015-01-21 18:24:51 -05:00
```ruby
create_table :versions do |t|
...
t.json :object # Full object changes
t.json :object_changes # Optional column-level changes
...
end
```
2015-01-29 17:52:56 -05:00
Note: You don't need to use a particular serializer for the PostgreSQL `JSON` column type.
2015-01-22 14:45:08 -05:00
2014-12-29 14:55:04 -05:00
## SerializedAttributes support
PaperTrail has a config option that can be used to enable/disable whether PaperTrail attempts to utilize
`ActiveRecord` 's `serialized_attributes` feature. Note: This is enabled by default when PaperTrail is used
with `ActiveRecord` version < `4.2` , and disabled by default when used with ActiveRecord `4.2.x` . Since
`serialized_attributes` will be removed in `ActiveRecord` version `5.0` , this configuration value
has no functionality when PaperTrail is used with version `5.0` or greater.
```ruby
# Enable support
>> PaperTrail.config.serialized_attributes = true
# Disable support
2014-12-29 21:06:39 -05:00
>> PaperTrail.config.serialized_attributes = false
2014-12-29 14:55:04 -05:00
# Get current setting
>> PaperTrail.serialized_attributes?
```
2013-05-23 15:56:19 -04:00
## Limiting the number of versions created per object instance
2014-04-08 14:16:54 -04:00
If you are wary of your `versions` table growing to an unwieldy size, or just don't care to track more than a certain number of versions per object,
2013-05-23 15:59:07 -04:00
there is a configuration option that can be set to cap the number of versions saved per object. Note that this value must be numeric, and it only applies to
versions other than `create` events (which will always be preserved if they are stored).
2013-05-23 15:56:19 -04:00
```ruby
2013-10-28 12:30:47 -04:00
# will make it so that a maximum of 4 versions will be stored for each object
# (the 3 most recent ones plus a `create` event)
2013-05-23 15:59:07 -04:00
>> PaperTrail.config.version_limit = 3
# disables/removes the version limit
>> PaperTrail.config.version_limit = nil
2013-05-23 15:56:19 -04:00
```
2010-06-23 06:52:00 -04:00
## Deleting Old Versions
Over time your `versions` table will grow to an unwieldy size. Because each version is self-contained (see the Diffing section above for more) you can simply delete any records you don't want any more. For example:
2011-12-10 07:09:18 -05:00
```sql
sql> delete from versions where created_at < 2010-06-01 ;
```
2010-06-23 06:52:00 -04:00
2011-12-10 07:09:18 -05:00
```ruby
2013-05-29 17:19:05 -04:00
>> PaperTrail::Version.delete_all ["created_at < ?", 1.week.ago]
2011-12-10 07:09:18 -05:00
```
2010-06-23 06:52:00 -04:00
2009-05-27 13:29:58 -04:00
## Testing
2013-10-28 12:30:47 -04:00
You may want to turn PaperTrail off to speed up your tests. See the [Turning PaperTrail Off/On ](#turning-papertrail-offon ) section above for tips on usage with `Test::Unit` .
2013-08-27 15:12:33 -04:00
### RSpec
2009-05-27 13:29:58 -04:00
2014-12-29 15:42:49 -05:00
PaperTrail provides a helper that works with [RSpec ](https://github.com/rspec/rspec )
to make it easier to control when `PaperTrail` is enabled during testing.
If you wish to use the helper, you will need to require it in your RSpec test helper like so:
```ruby
# spec/rails_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__ )
require 'rspec/rails'
...
require 'paper_trail/frameworks/rspec'
```
When the helper is loaded, PaperTrail will be turned off for all tests by default.
2013-10-02 13:48:20 -04:00
When you wish to enable PaperTrail for a test you can either wrap the test in a `with_versioning` block, or pass in `:versioning => true` option to a spec block, like so:
2011-11-09 06:04:41 -05:00
2011-12-10 07:09:18 -05:00
```ruby
2013-08-27 15:12:33 -04:00
describe "RSpec test group" do
it 'by default, PaperTrail will be turned off' do
2014-10-07 23:58:51 -04:00
expect(PaperTrail).to_not be_enabled
2013-08-27 15:12:33 -04:00
end
with_versioning do
it 'within a `with_versioning` block it will be turned on' do
2014-10-07 23:58:51 -04:00
expect(PaperTrail).to be_enabled
2013-08-27 15:12:33 -04:00
end
end
it 'can be turned on at the `it` or `describe` level like this', :versioning => true do
2014-10-07 23:58:51 -04:00
expect(PaperTrail).to be_enabled
2011-12-10 07:09:18 -05:00
end
end
```
2011-11-09 06:04:41 -05:00
2013-08-27 15:12:33 -04:00
The helper will also reset the `PaperTrail.whodunnit` value to `nil` before each test to help prevent data spillover between tests.
If you are using PaperTrail with Rails, the helper will automatically set the `PaperTrail.controller_info` value to `{}` as well, again, to help prevent data spillover between tests.
There is also a `be_versioned` matcher provided by PaperTrail's RSpec helper which can be leveraged like so:
```ruby
class Widget < ActiveRecord::Base
end
describe Widget do
2014-10-07 23:58:51 -04:00
it "is not versioned by default" do
2014-10-09 18:06:17 -04:00
is_expected.to_not be_versioned
2014-10-07 23:58:51 -04:00
end
2013-08-27 15:12:33 -04:00
describe "add versioning to the `Widget` class" do
before(:all) do
class Widget < ActiveRecord::Base
has_paper_trail
end
end
2014-10-07 23:58:51 -04:00
it "enables paper trail" do
2014-10-09 18:06:17 -04:00
is_expected.to be_versioned
2014-10-07 23:58:51 -04:00
end
2013-08-27 15:12:33 -04:00
end
end
```
2009-05-27 13:29:58 -04:00
2014-07-09 08:47:15 -04:00
It is also possible to do assertions on the versions using `have_a_version_with` matcher
```
describe '`have_a_version_with` matcher' do
before do
widget.update_attributes!(:name => 'Leonard', :an_integer => 1 )
widget.update_attributes!(:name => 'Tom')
widget.update_attributes!(:name => 'Bob')
end
it "is possible to do assertions on versions" do
2014-10-07 23:58:51 -04:00
expect(widget).to have_a_version_with :name => 'Leonard', :an_integer => 1
expect(widget).to have_a_version_with :an_integer => 1
expect(widget).to have_a_version_with :name => 'Tom'
2014-07-09 08:47:15 -04:00
end
end
```
2013-08-27 16:16:06 -04:00
### Cucumber
2013-10-02 13:48:20 -04:00
PaperTrail provides a helper for [Cucumber ](http://cukes.info ) that works similar to the RSpec helper.
2014-12-29 15:42:49 -05:00
If you wish to use the helper, you will need to require in your cucumber helper like so:
```ruby
# features/support/env.rb
ENV["RAILS_ENV"] ||= "cucumber"
require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')
...
require 'paper_trail/frameworks/cucumber'
```
When the helper is loaded, PaperTrail will be turned off for all scenarios by a `before` hook added by the helper by default.
2013-08-27 16:16:06 -04:00
When you wish to enable PaperTrail for a scenario, you can wrap code in a `with_versioning` block in a step, like so:
```ruby
Given /I want versioning on my model/ do
with_versioning do
# PaperTrail will be turned on for all code inside of this block
end
end
```
The helper will also reset the `PaperTrail.whodunnit` value to `nil` before each test to help prevent data spillover between tests.
If you are using PaperTrail with Rails, the helper will automatically set the `PaperTrail.controller_info` value to `{}` as well, again, to help prevent data spillover between tests.
2013-10-02 13:48:20 -04:00
### Spork
If you wish to use the `RSpec` or `Cucumber` helpers with [Spork ](https://github.com/sporkrb/spork ), you will need to
manually require the helper(s) in your `prefork` block on your test helper, like so:
```ruby
2014-12-29 15:42:49 -05:00
# spec/rails_helper.rb
2013-10-02 13:48:20 -04:00
require 'spork'
Spork.prefork do
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
2014-12-29 15:42:49 -05:00
require 'spec_helper'
2013-10-02 13:48:20 -04:00
require File.expand_path("../../config/environment", __FILE__ )
require 'rspec/rails'
require 'paper_trail/frameworks/rspec'
require 'paper_trail/frameworks/cucumber'
...
end
```
2014-06-06 14:51:03 -04:00
### Zeus or Spring
2013-10-02 13:48:20 -04:00
2014-06-06 14:51:03 -04:00
If you wish to use the `RSpec` or `Cucumber` helpers with [Zeus ](https://github.com/burke/zeus ) or [Spring ](https://github.com/rails/spring ), you will need to
2013-10-02 13:48:20 -04:00
manually require the helper(s) in your test helper, like so:
```ruby
2014-12-29 15:42:49 -05:00
# spec/rails_helper.rb
2013-10-02 13:48:20 -04:00
ENV["RAILS_ENV"] ||= 'test'
2014-12-29 15:42:49 -05:00
require 'spec_helper'
2013-10-02 13:48:20 -04:00
require File.expand_path("../../config/environment", __FILE__ )
require 'rspec/rails'
require 'paper_trail/frameworks/rspec'
```
2014-03-18 16:34:25 -04:00
## Testing PaperTrail
2014-03-16 11:24:09 -04:00
2014-12-22 13:36:47 -05:00
Paper Trail has facilities to test against Postgres, Mysql and SQLite. To switch between DB engines you will need to export the DB variable for the engine you wish to test aganist.
2014-03-16 11:24:09 -04:00
2014-07-09 08:47:15 -04:00
Though be aware we do not have the abilty to create the db's (except sqlite) for you. You can look at .travis.yml before_script for an example of how to create the db's needed.
2014-03-16 11:24:09 -04:00
2014-03-18 16:34:25 -04:00
```
export DB=postgres
export DB=mysql
export DB=sqlite # this is default
```
2014-03-16 11:24:09 -04:00
2010-02-23 12:07:00 -05:00
## Articles
2014-10-07 22:55:20 -04:00
* [Jutsu #8 - Version your RoR models with PaperTrail ](http://samurails.com/gems/papertrail/ ), [Thibault ](http://samurails.com/about-me/ ), 29th September 2014
2014-06-10 11:51:52 -04:00
* [Versioning with PaperTrail ](http://www.sitepoint.com/versioning-papertrail ), [Ilya Bodrov ](http://www.sitepoint.com/author/ibodrov ), 10th April 2014
2014-04-03 15:51:23 -04:00
* [Using PaperTrail to track stack traces ](http://rubyrailsexpert.com/?p=36 ), T James Corcoran's blog, 1st October 2013.
* [RailsCast #255 - Undo with PaperTrail ](http://railscasts.com/episodes/255-undo-with-paper-trail ), 28th February 2011.
* [Keep a Paper Trail with PaperTrail ](http://www.linux-mag.com/id/7528 ), Linux Magazine, 16th September 2009.
2010-02-23 12:07:00 -05:00
2009-06-23 05:39:16 -04:00
## Problems
Please use GitHub's [issue tracker ](http://github.com/airblade/paper_trail/issues ).
2009-11-23 11:52:42 -05:00
## Contributors
Many thanks to:
2014-06-03 16:25:07 -04:00
* [Dmitry Polushkin ](https://github.com/dmitry )
2014-05-09 12:08:02 -04:00
* [Russell Osborne ](https://github.com/rposborne )
2009-11-23 11:52:42 -05:00
* [Zachery Hostens ](http://github.com/zacheryph )
2010-02-18 12:34:10 -05:00
* [Jeremy Weiskotten ](http://github.com/jeremyw )
2010-03-19 10:19:01 -04:00
* [Phan Le ](http://github.com/revo )
* [jdrucza ](http://github.com/jdrucza )
2010-10-11 12:50:38 -04:00
* [conickal ](http://github.com/conickal )
2010-10-28 05:41:25 -04:00
* [Thibaud Guillaume-Gentil ](http://github.com/thibaudgg )
* Danny Trelogan
2010-10-28 13:19:46 -04:00
* [Mikl Kurkov ](http://github.com/mkurkov )
2010-11-19 04:13:48 -05:00
* [Franco Catena ](https://github.com/francocatena )
2011-02-21 04:45:12 -05:00
* [Emmanuel Gomez ](https://github.com/emmanuel )
2011-02-25 10:30:13 -05:00
* [Matthew MacLeod ](https://github.com/mattmacleod )
2011-03-31 12:02:03 -04:00
* [benzittlau ](https://github.com/benzittlau )
2011-03-31 12:48:54 -04:00
* [Tom Derks ](https://github.com/EgoH )
2011-04-05 04:10:41 -04:00
* [Jonas Hoglund ](https://github.com/jhoglund )
2011-04-07 04:45:07 -04:00
* [Stefan Huber ](https://github.com/MSNexploder )
2011-04-28 11:17:21 -04:00
* [thinkcast ](https://github.com/thinkcast )
2011-05-06 06:24:04 -04:00
* [Dominik Sander ](https://github.com/dsander )
2011-05-16 06:16:33 -04:00
* [Burke Libbey ](https://github.com/burke )
2011-06-21 11:12:13 -04:00
* [6twenty ](https://github.com/6twenty )
2011-07-11 10:58:35 -04:00
* [nir0 ](https://github.com/nir0 )
2011-07-13 05:22:05 -04:00
* [Eduard Tsech ](https://github.com/edtsech )
2011-08-22 10:53:03 -04:00
* [Mathieu Arnold ](https://github.com/mat813 )
2011-09-14 04:19:24 -04:00
* [Nicholas Thrower ](https://github.com/throwern )
2011-11-09 05:06:26 -05:00
* [Benjamin Curtis ](https://github.com/stympy )
2011-11-09 05:38:07 -05:00
* [Peter Harkins ](https://github.com/pushcx )
2011-11-25 02:54:22 -05:00
* [Mohd Amree ](https://github.com/amree )
2012-01-18 03:07:14 -05:00
* [Nikita Cernovs ](https://github.com/nikitachernov )
2012-03-12 05:39:24 -04:00
* [Jason Noble ](https://github.com/jasonnoble )
2012-03-12 07:15:29 -04:00
* [Jared Mehle ](https://github.com/jrmehle )
2012-03-12 09:04:02 -04:00
* [Eric Schwartz ](https://github.com/emschwar )
2012-03-22 09:10:04 -04:00
* [Ben Woosley ](https://github.com/Empact )
2012-03-22 09:16:47 -04:00
* [Philip Arndt ](https://github.com/parndt )
2012-04-13 03:53:37 -04:00
* [Daniel Vydra ](https://github.com/dvydra )
2012-11-28 11:34:33 -05:00
* [Byron Bowerman ](https://github.com/BM5k )
* [Nicolas Buduroi ](https://github.com/budu )
* [Pikender Sharma ](https://github.com/pikender )
* [Paul Brannan ](https://github.com/cout )
* [Ben Morrall ](https://github.com/bmorrall )
* [Yves Senn ](https://github.com/senny )
* [Ben Atkins ](https://github.com/fullbridge-batkins )
2012-12-28 01:16:47 -05:00
* [Tyler Rick ](https://github.com/TylerRick )
* [Bradley Priest ](https://github.com/bradleypriest )
2013-01-23 10:00:22 -05:00
* [David Butler ](https://github.com/dwbutler )
2013-08-27 15:12:33 -04:00
* [Paul Belt ](https://github.com/belt )
2013-09-19 16:18:02 -04:00
* [Vlad Bokov ](https://github.com/razum2um )
2013-10-17 22:59:50 -04:00
* [Sean Marcia ](https://github.com/SeanMarcia )
2013-10-29 14:09:35 -04:00
* [Chulki Lee ](https://github.com/chulkilee )
2014-03-11 17:55:44 -04:00
* [Lucas Souza ](https://github.com/lucasas )
2014-03-18 16:34:25 -04:00
* [Russell Osborne ](https://github.com/rposborne )
2014-12-27 22:32:03 -05:00
* [Ben Li ](https://github.com/bli )
* [Felix Liu ](https://github.com/lyfeyaj )
2009-11-23 11:52:42 -05:00
2009-05-27 11:21:20 -04:00
## Inspirations
* [Simply Versioned ](http://github.com/github/simply_versioned )
* [Acts As Audited ](http://github.com/collectiveidea/acts_as_audited )
## Intellectual Property
2011-02-09 05:54:06 -05:00
Copyright (c) 2011 Andy Stewart (boss@airbladesoftware.com).
2009-05-27 11:21:20 -04:00
Released under the MIT licence.