Skip to content

Repository files navigation

PaperTrail

Build StatusDependency Status

Track changes to your models, for auditing or versioning. See how a model looked at any stage in its lifecycle, revert it to any version, or restore it after it has been destroyed.

Documentation

VersionDocumentation
5 (unreleased)https://github.com/airblade/paper_trail/blob/master/README.md
4https://github.com/airblade/paper_trail/blob/4.0-stable/README.md
3https://github.com/airblade/paper_trail/blob/3.0-stable/README.md
2https://github.com/airblade/paper_trail/blob/2.7-stable/README.md
1https://github.com/airblade/paper_trail/blob/rails2/README.md

Table of Contents

Compatibility

paper_trailbranchtagsrubyactiverecord
5 (unreleased)masternone>= 1.9.3>= 3.0, < 6
44.0-stablev4.x>= 1.8.7>= 3.0, < 6
33.0-stablev3.x>= 1.8.7>= 3.0, < 5
22.7-stablev2.x>= 1.8.7>= 3.0, < 4
1rails2v1.x>= 1.8.7>= 2.3, < 3

Installation

  1. Add PaperTrail to your Gemfile.

    gem 'paper_trail'

  2. Add a versions table to your database.

    bundle exec rails generate paper_trail:install
    bundle exec rake db:migrate
    

    If using rails_admin, you must enable the experimental Associations feature.

  3. Add has_paper_trail to the models you want to track.

    classWidget < ActiveRecord::Basehas_paper_trailend
  4. If your controllers have a current_user method, you can easily track who is responsible for changes by adding a controller callback.

    classApplicationControllerbefore_filter:set_paper_trail_whodunnitend

Basic Usage

Your models now have a versions method which returns the "paper trail" of changes to your model.

widget=Widget.find42widget.versions# [<PaperTrail::Version>, <PaperTrail::Version>, ...]

Once you have a version, you can find out what happened:

v=widget.versions.lastv.event# 'update', 'create', or 'destroy'v.created_at# When the `event` occurredv.whodunnit# If the update was via a controller and the# controller has a current_user method, returns the# id of the current user as a string.widget=v.reify# The widget as it was before the update# (nil for a create event)

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.

widget=Widget.find153widget.name# 'Doobly'# Add has_paper_trail to Widget model.widget.versions# []widget.update_attributes:name=>'Wotsit'widget.versions.last.reify.name# 'Doobly'widget.versions.last.event# 'update'

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.

Here's a helpful table showing what PaperTrail stores:

Eventcreateupdatedestroy
Model Beforenilwidgetwidget
Model Afterwidgetwidgetnil

PaperTrail stores the values in the Model Before column. Most other auditing/versioning plugins store the After column.

API Summary

When you declare has_paper_trail in your model, you get these methods:

classWidget < ActiveRecord::Basehas_paper_trailend# Returns this widget's versions. You can customise the name of the# association.widget.versions# Return the version this widget was reified from, or nil if it is live.# You can customise the name of the method.widget.version# Returns true if this widget is the current, live one; or false if it is from# a previous version.widget.live?# Returns who put the widget into its current state.widget.paper_trail_originator# Returns the widget (not a version) as it looked at the given timestamp.widget.version_at(timestamp)# Returns the widget (not a version) as it was most recently.widget.previous_version# Returns the widget (not a version) as it became next.widget.next_version# Generates a version for a `touch` event (`widget.touch` does NOT generate a# version)widget.touch_with_version# Turn PaperTrail off for all widgets.Widget.paper_trail_off!# Turn PaperTrail on for all widgets.Widget.paper_trail_on!# Is PaperTrail enabled for Widget, the class?Widget.paper_trail_enabled_for_model?# Is PaperTrail enabled for widget, the instance?widget.paper_trail_enabled_for_model?

And a PaperTrail::Version instance has these methods:

# Returns the item restored from this version.version.reify(options={})# Return a new item from this versionversion.reify(dup: true)# Returns who put the item into the state stored in this version.version.paper_trail_originator# Returns who changed the item from the state it had in this version.version.terminatorversion.whodunnitversion.version_author# Returns the next version.version.next# Returns the previous version.version.previous# Returns the index of this version in all the versions.version.index# Returns the event that caused this version (create|update|destroy).version.event# Query versions objects by attributes.PaperTrail::Version.where_object(attr1: val1,attr2: val2)# Query versions object_changes field by attributes (requires# `object_changes` column on versions table).# Also can't guarantee consistent query results for numeric values# due to limitations of SQL wildcard matchers against the serialized objects.PaperTrail::Version.where_object_changes(attr1: val1)

In your controllers you can override these methods:

# Returns the user who is responsible for any changes that occur.# Defaults to current_user.user_for_paper_trail# Returns any information about the controller or request that you want# PaperTrail to store alongside any changes that occur.info_for_paper_trail

Choosing Lifecycle Events To Monitor

You can choose which events to track with the on option. For example, to ignore create events:

classArticle < ActiveRecord::Basehas_paper_trail:on=>[:update,:destroy]end

has_paper_trail installs callbacks for these lifecycle events. If there are other callbacks in your model, their order relative to those installed by PaperTrail may matter, so be aware of any potential interactions.

You may also have the PaperTrail::Version model save a custom string in it's event field instead of the typical create, update, destroy. 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.

a=Article.createa.versions.size# 1a.versions.last.event# 'create'a.paper_trail_event='update title'a.update_attributes:title=>'My Title'a.versions.size# 2a.versions.last.event# 'update title'a.paper_trail_event=nila.update_attributes:title=>"Alternate"a.versions.size# 3a.versions.last.event# 'update'

Controlling the Order of AR Callbacks

The has_paper_trail method installs AR callbacks. If you need to control their order, use the paper_trail_on_* methods.

classArticle < ActiveRecord::Base# Include PaperTrail, but do not add any callbacks yet. Passing the# empty array to `:on` omits callbacks.has_paper_trail:on=>[]# Add callbacks in the order you need.paper_trail_on_destroy# add destroy callbackpaper_trail_on_update# etc.paper_trail_on_createend

The paper_trail_on_destroy method can be further configured to happen :before or :after the destroy event. In PaperTrail 4, the default is :after. In PaperTrail 5, the default will be :before, to support ActiveRecord 5. (see paper-trail-gem#683)

Choosing When To Save New Versions

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:

classTranslation < ActiveRecord::Basehas_paper_trail:if=>Proc.new{ |t| t.language_code == 'US'},:unless=>Proc.new{ |t| t.type == 'DRAFT'}end

Choosing Based on Changed Attributes

Starting with PaperTrail 4.0, versions are saved during an after-callback. If you decide whether to save a new version based on changed attributes, please use attribute_name_was instead of attribute_name.

Choosing Attributes To Monitor

You can ignore changes to certain attributes like this:

classArticle < ActiveRecord::Basehas_paper_trail:ignore=>[:title,:rating]end

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:

a=Article.createa.versions.length# 1a.update_attributes:title=>'My Title',:rating=>3a.versions.length# 1a.update_attributes:title=>'Greeting',:content=>'Hello'a.versions.length# 2a.previous_version.title# 'My Title'

Or, you can specify a list of all attributes you care about:

classArticle < ActiveRecord::Basehas_paper_trail:only=>[:title]end

This means that only changes to the title will save a version of the article:

a=Article.createa.versions.length# 1a.update_attributes:title=>'My Title'a.versions.length# 2a.update_attributes:content=>'Hello'a.versions.length# 2a.previous_version.content# nil

The :ignore and :only options can also accept Hash arguments, where the :

classArticle < ActiveRecord::Basehas_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:

a=Article.createa.versions.length# 1a.update_attributes:content=>'Hello'a.versions.length# 2a.update_attributes:title=>'My Title'a.versions.length# 3a.update_attributes:content=>'Hai'a.versions.length# 3a.previous_version.content# "Hello"a.update_attributes:title=>'Dif Title'a.versions.length# 4a.previous_version.content# "Hai"

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.

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.

For example:

classArticle < ActiveRecord::Basehas_paper_trail:skip=>[:file_upload]end

Turning PaperTrail Off

PaperTrail is on by default, but sometimes you don't want to record versions.

Per Process

Turn PaperTrail off for all threads in a ruby process.

PaperTrail.enabled=false

This is commonly used to speed up tests. See Testing below.

There is also a rails config option that does the same thing.

# in config/environments/test.rbconfig.paper_trail.enabled=false

Per Request

Add a paper_trail_enabled_for_controller method to your controller.

classApplicationController < ActionController::Basedefpaper_trail_enabled_for_controllerrequest.user_agent != 'Disable User-Agent'endend

Per Class

Widget.paper_trail_off!Widget.paper_trail_on!

Per Method

You can call a method without creating a new version using without_versioning. It takes either a method name as a symbol:

@widget.without_versioning:destroy

Or a block:

@widget.without_versioningdo@widget.update_attributes:name=>'Ford'end

Limiting the Number of Versions Created

Configure version_limit to cap the number of versions saved per record. This does not apply to create events.

# Limit: 4 versions per record (3 most recent, plus a `create` event)PaperTrail.config.version_limit=3# Remove the limitPaperTrail.config.version_limit=nil

Reverting And Undeleting A Model

PaperTrail makes reverting to a previous version easy:

widget=Widget.find42widget.update_attributes:name=>'Blah blah'# Time passes....widget=widget.previous_version# the widget as it was before the updatewidget.save# reverted

Alternatively you can find the version at a given time:

widget=widget.version_at(1.day.ago)# the widget as it was one day agowidget.save# reverted

Note version_at gives you the object, not a version, so you don't need to call reify.

Undeleting is just as simple:

widget=Widget.find42widget.destroy# Time passes....widget=PaperTrail::Version.find(153).reify# the widget as it was before destructionwidget.save# the widget lives!

You could even use PaperTrail to implement an undo system, Ryan Bates has!

If your model uses optimistic locking don't forget to increment your lock_version before saving or you'll get a StaleObjectError.

Navigating Versions

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.

live_widget=Widget.find42live_widget.versions.length# 4 for examplewidget=live_widget.previous_version# => widget == live_widget.versions.last.reifywidget=widget.previous_version# => widget == live_widget.versions[-2].reifywidget=widget.next_version# => widget == live_widget.versions.last.reifywidget.next_version# live_widget

If instead you have a particular version of an item you can navigate to the previous and next versions.

widget=Widget.find42version=widget.versions[-2]# assuming widget has several versionsprevious=version.previousnext=version.next

You can find out which of an item's versions yours is:

current_version_number=version.index# 0-based

If you got an item by reifying one of its versions, you can navigate back to the version it came from:

latest_version=Widget.find(42).versions.lastwidget=latest_version.reifywidget.version == latest_version# true

You can find out whether a model instance is the current, live one -- or whether it came instead from a previous version -- with live?:

widget=Widget.find42widget.live?# truewidget=widget.previous_versionwidget.live?# false

And you can perform WHERE queries for object versions based on attributes:

# All versions that meet these criteria.PaperTrail::Version.where_object(content: "Hello",title: "Article")

Diffing Versions

There are two scenarios: diffing adjacent versions and diffing non-adjacent versions.

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:

widget=Widget.create:name=>'Bob'widget.versions.last.changeset# {# "name"=>[nil, "Bob"],# "created_at"=>[nil, 2015-08-10 04:10:40 UTC],# "updated_at"=>[nil, 2015-08-10 04:10:40 UTC],# "id"=>[nil, 1]# }widget.update_attributes:name=>'Robert'widget.versions.last.changeset# {# "name"=>["Bob", "Robert"],# "updated_at"=>[2015-08-10 04:13:19 UTC, 2015-08-10 04:13:19 UTC]# }widget.destroywidget.versions.last.changeset# {}

The object_changes are only stored for creation and updates, not when an object is destroyed.

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:

For diffing two strings:

  • 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: 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.
  • diff-lcs: old-school, line-wise diffs.

For diffing two ActiveRecord objects:

If you wish to selectively record changes for some models but not others you can opt out of recording changes by passing :save_changes => false to your has_paper_trail method declaration.

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:

sql>deletefrom versions where created_at <2010-06-01;
PaperTrail::Version.delete_all["created_at < ?",1.week.ago]

Finding Out Who Was Responsible For A Change

Set PaperTrail.whodunnit=, and that value will be stored in the version's whodunnit column.

PaperTrail.whodunnit='Andy Stewart'widget.update_attributes:name=>'Wibble'widget.versions.last.whodunnit# Andy Stewart

If your controller has a current_user method, PaperTrail provides a before_filter that will assign current_user.id to PaperTrail.whodunnit. You can add this before_filter to your ApplicationController.

classApplicationControllerbefore_filter:set_paper_trail_whodunnitend

You may want set_paper_trail_whodunnit 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:

classApplicationControllerdefuser_for_paper_traillogged_in? ? current_member.id : 'Public user'# or whateverendend

See also: Setting whodunnit in the rails console

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:

PaperTrail.whodunnit='Andy Stewart'widget.whodunnit('Lucas Souza')dowidget.update_attributes:name=>'Wibble'endwidget.versions.last.whodunnit# Lucas Souzawidget.update_attributes:name=>'Clair'widget.versions.last.whodunnit# Andy Stewartwidget.whodunnit('Ben Atkins'){ |w| w.update_attributes:name=>'Beth'}# this syntax also workswidget.versions.last.whodunnit# Ben Atkins

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.

To find out who made a version's object look that way, use version.paper_trail_originator. And to find out who made a "live" object look like it does, call paper_trail_originator on the object.

widget=Widget.find153# assume widget has 0 versionsPaperTrail.whodunnit='Alice'widget.update_attributes:name=>'Yankee'widget.paper_trail_originator# 'Alice'PaperTrail.whodunnit='Bob'widget.update_attributes:name=>'Zulu'widget.paper_trail_originator# 'Bob'first_version,last_version=widget.versions.first,widget.versions.lastfirst_version.whodunnit# 'Alice'first_version.paper_trail_originator# nilfirst_version.terminator# 'Alice'last_version.whodunnit# 'Bob'last_version.paper_trail_originator# 'Alice'last_version.terminator# 'Bob'

Storing an ActiveRecord globalid in whodunnit

If you would like whodunnit to return an ActiveRecord object instead of a string, please try the paper_trail-globalid gem.

Associations

Experimental feature, see caveats below.

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.

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. To restore Belongs-To association, use option :belongs_to => true. For example:

classLocation < ActiveRecord::Basebelongs_to:treasurehas_paper_trailendclassTreasure < ActiveRecord::Basehas_one:locationhas_paper_trailendtreasure.amount# 100treasure.location.latitude# 12.345treasure.update_attributes:amount=>153treasure.location.update_attributes:latitude=>54.321t=treasure.versions.last.reify(:has_one=>true)t.amount# 100t.location.latitude# 12.345

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).

treasure.amount# 100treasure.location.latitude# 12.345Treasure.transactiondotreasure.location.update_attributes:latitude=>54.321treasure.update_attributes:amount=>153endt=treasure.versions.last.reify(:has_one=>true)t.amount# 100t.location.latitude# 12.345, instead of 54.321

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. Note that mark_for_destruction only has an effect on associations marked with autosave: true.

classWidget < ActiveRecord::Basehas_paper_trailhas_one:wotsit,autosave: trueendclassWotsit < ActiveRecord::Basehas_paper_trailbelongs_to:widgetendwidget=Widget.create(:name=>'widget_0')widget.update_attributes(:name=>'widget_1')widget.create_wotsit(:name=>'wotsit')widget_0=widget.versions.last.reify(:has_one=>true)widget_0.wotsit# nilwidget_0=widget.versions.last.reify(:has_one=>true,:mark_for_destruction=>true)widget_0.wotsit.marked_for_destruction?# truewidget_0.save!widget.reload.wotsit# nil

Caveats:

  1. Not compatible with transactional tests, aka. transactional fixtures. This is a known issue #542 that we'd like to solve.
  2. Requires database timestamp columns with fractional second precision.
    • Sqlite and postgres timestamps have fractional second precision by default. MySQL timestamps do not. Furthermore, MySQL 5.5 and earlier do not support fractional second precision at all.
    • Also, support for fractional seconds in MySQL was not added to rails until ActiveRecord 4.2 (rails/rails#14359).
  3. PaperTrail can't restore an association properly if the association record can be updated to replace its parent model (by replacing the foreign key)
  4. 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.
  5. PaperTrail only reifies the first level of associations, i.e., it does not reify any associations of its associations, and so on.
  6. 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:

Given these models:

classBook < ActiveRecord::Basehas_many:authorships,:dependent=>:destroyhas_many:authors,:through=>:authorships,:source=>:personhas_paper_trailendclassAuthorship < ActiveRecord::Basebelongs_to:bookbelongs_to:personhas_paper_trail# NOTEendclassPerson < ActiveRecord::Basehas_many:authorships,:dependent=>:destroyhas_many:books,:through=>:authorshipshas_paper_trailend

Then each of the following will store authorship versions:

@book.authors << @dostoyevsky@book.authors.create:name=>'Tolstoy'@book.authorships.last.destroy@book.authorships.clear@book.author_ids=[@solzhenistyn.id,@dostoyevsky.id]

But none of these will:

@book.authors.delete@tolstoy@book.author_ids=[]@book.authors=[]

Having said that, you can apparently get all these working (I haven't tested it myself) with this patch:

# In config/initializers/active_record_patch.rbmoduleActiveRecord# = Active Record Has Many Through AssociationmoduleAssociationsclassHasManyThroughAssociation < HasManyAssociation#:nodoc:alias_method:original_delete_records,:delete_recordsdefdelete_records(records,method)method ||= :destroyoriginal_delete_records(records,method)endendendend

See issue 113 for a discussion about this.

Storing Metadata

You can store arbitrary model-level metadata alongside each version like this:

classArticle < ActiveRecord::Basebelongs_to:authorhas_paper_trail:meta=>{:author_id=>:author_id,:word_count=>:count_words,:answer=>42}defcount_words153endend

PaperTrail will call your proc with the current article and store the result in the author_id column of the versions table. Don't forget to add any such columns to your versions table.

Advantages of Metadata

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:

PaperTrail::Version.where(:author_id=>author_id)

Metadata from Controllers

You can also store any information you like from your controller. Override the info_for_paper_trail method in your controller to return a hash whose keys correspond to columns in your versions table.

classApplicationControllerdefinfo_for_paper_trail{:ip=>request.remote_ip,:user_agent=>request.user_agent}endend

Protected Attributes and Metadata

If you are using rails 3 or the protected_attributes gem you must declare your metadata columns to be attr_accessible.

# app/models/paper_trail/version.rbmodulePaperTrailclassVersion < ActiveRecord::BaseincludePaperTrail::VersionConcernattr_accessible:author_id,:word_count,:answerendend

If you're using strong_parameters instead of protected_attributes then there is no need to use attr_accessible.

Custom Version Classes

You can specify custom version subclasses with the :class_name option:

classPostVersion < PaperTrail::Version# custom behaviour, e.g:self.table_name=:post_versionsendclassPost < ActiveRecord::Basehas_paper_trail:class_name=>'PostVersion'end

Unlike ActiveRecord's class_name, you'll have to supply the complete module path to the class (e.g. Foo::BarVersion if your class is inside the module Foo).

Advantages

  1. For models which have a lot of versions, storing each model's versions in a separate table can improve the performance of certain database queries.
  2. Store different version metadata for different models.

Configuration

If you are using Postgres, you should also define the sequence that your custom version class will use:

classPostVersion < PaperTrail::Versionself.table_name=:post_versionsself.sequence_name=:post_versions_id_seqend

If you only use custom version classes and don't have a versions table, you must let ActiveRecord know that the PaperTrail::Version class is an abstract_class.

# app/models/paper_trail/version.rbmodulePaperTrailclassVersion < ActiveRecord::BaseincludePaperTrail::VersionConcernself.abstract_class=trueendend

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:

classPost < ActiveRecord::Basehas_paper_trail:versions=>:paper_trail_versions,:version=>:paper_trail_version# Existing versions method. We don't want to clash.defversions
...
end# Existing version method. We don't want to clash.defversion
...
endend

Custom Serializer

By default, PaperTrail stores your changes as a YAML dump. You can override this with the serializer config option:

PaperTrail.serializer=MyCustomSerializer

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:

PostgreSQL JSON column type support

If you use PostgreSQL, and would like to store your object (and/or object_changes) data in a column of type json or type jsonb, specify json instead of text for these columns in your migration:

create_table:versionsdo |t|
...
t.json:object# Full object changest.json:object_changes# Optional column-level changes
...
end

If you use the PostgreSQL json or jsonb column type, you do not need to specify a PaperTrail.serializer.

Convert existing YAML data to JSON

If you've been using PaperTrail for a while with the default YAML serializer and you want to switch to JSON or JSONB, you're in a bit of a bind because there's no automatic way to migrate your data. The first (slow) option is to loop over every record and parse it in Ruby, then write to a temporary column:

add_column:versions,:object,:new_object,:jsonb# or :jsonPaperTrail::Version.reset_column_informationPaperTrail::Version.find_eachdo |version|
version.update_column:new_object,YAML.load(version.object)endremove_column:versions,:objectrename_column:versions,:new_object,:object

This technique can be very slow if you have a lot of data. Though slow, it is safe in databases where transactions are protected against DDL, such as Postgres. In databases without such protection, such as MySQL, a table lock may be necessary.

If the above technique is too slow for your needs, and you're okay doing without PaperTrail data temporarily, you can create the new column without converting the data.

rename_column:versions,:object,:old_objectadd_column:versions,:object,:jsonb# or :json

After that migration, your historical data still exists as YAML, and new data will be stored as JSON. Next, convert records from YAML to JSON using a background script.

PaperTrail::Version.where.not(old_object: nil).find_eachdo |version|
version.update_columnsold_object: nil,object: YAML.load(version.old_object)end

Finally, in another migration, remove the old column.

remove_column:versions,:old_object

If you use the optional object_changes column, don't forget to convert it also, using the same technique.

Convert a Column from Text to JSON

If your object column already contains JSON data, and you want to change its data type to json or jsonb, you can use the following DDL. Of course, if your object column contains YAML, you must first convert the data to JSON (see above) before you can change the column type.

Using SQL:

altertable versions
alter column object type jsonb
using object::jsonb;

Using ActiveRecord:

classConvertVersionsObjectToJson < ActiveRecord::Migrationdefupchange_column:versions,:object,'jsonb USING object::jsonb'enddefdownchange_column:versions,:object,'text USING object::text'endend

Testing

You may want to turn PaperTrail off to speed up your tests. See Turning PaperTrail Off above.

Minitest

First, disable PT for the entire ruby process.

# in config/environments/test.rbconfig.after_initializedoPaperTrail.enabled=falseend

Then, to enable PT for specific tests, you can add a with_versioning test helper method.

# in test/test_helper.rbdefwith_versioningwas_enabled=PaperTrail.enabled?was_enabled_for_controller=PaperTrail.enabled_for_controller?PaperTrail.enabled=truePaperTrail.enabled_for_controller=truebeginyieldensurePaperTrail.enabled=was_enabledPaperTrail.enabled_for_controller=was_enabled_for_controllerendend

Then, use the helper in your tests.

test"something that needs versioning"dowith_versioningdo# your testendend

RSpec

PaperTrail provides a helper, paper_trail/frameworks/rspec.rb, that works with RSpec to make it easier to control when PaperTrail is enabled during testing.

# spec/rails_helper.rbENV["RAILS_ENV"] ||= 'test'require'spec_helper'requireFile.expand_path("../../config/environment",__FILE__)require'rspec/rails'
...
require'paper_trail/frameworks/rspec'

With the helper loaded, PaperTrail will be turned off for all tests by default. 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.

describe"RSpec test group"doit'by default, PaperTrail will be turned off'doexpect(PaperTrail).to_notbe_enabledendwith_versioningdoit'within a `with_versioning` block it will be turned on'doexpect(PaperTrail).tobe_enabledendendit'can be turned on at the `it` or `describe` level like this',:versioning=>truedoexpect(PaperTrail).tobe_enabledendend

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:

classWidget < ActiveRecord::BaseenddescribeWidgetdoit"is not versioned by default"dois_expected.to_notbe_versionedenddescribe"add versioning to the `Widget` class"dobefore(:all)doclassWidget < ActiveRecord::Basehas_paper_trailendendit"enables paper trail"dois_expected.tobe_versionedendendend

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
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'
end
end

Cucumber

PaperTrail provides a helper for Cucumber that works similar to the RSpec helper.If you wish to use the helper, you will need to require in your cucumber helper like so:

# features/support/env.rbENV["RAILS_ENV"] ||= "cucumber"requireFile.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. When you wish to enable PaperTrail for a scenario, you can wrap code in a with_versioning block in a step, like so:

Given/I want versioning on my model/dowith_versioningdo# PaperTrail will be turned on for all code inside of this blockendend

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.

Spork

If you wish to use the RSpec or Cucumber helpers with Spork, you will need to manually require the helper(s) in your prefork block on your test helper, like so:

# spec/rails_helper.rbrequire'spork'Spork.preforkdo# This file is copied to spec/ when you run 'rails generate rspec:install'ENV["RAILS_ENV"] ||= 'test'require'spec_helper'requireFile.expand_path("../../config/environment",__FILE__)require'rspec/rails'require'paper_trail/frameworks/rspec'require'paper_trail/frameworks/cucumber'
...
end

Zeus or Spring

If you wish to use the RSpec or Cucumber helpers with Zeus or Spring, you will need to manually require the helper(s) in your test helper, like so:

# spec/rails_helper.rbENV["RAILS_ENV"] ||= 'test'require'spec_helper'requireFile.expand_path("../../config/environment",__FILE__)require'rspec/rails'require'paper_trail/frameworks/rspec'

Testing PaperTrail

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 against.

Though be aware we do not have the ability 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.

export DB=postgres
export DB=mysql
export DB=sqlite # this is default

Sinatra

In order to configure PaperTrail for usage with Sinatra, your Sinatra app must be using ActiveRecord 3 or 4. It is also recommended to use the Sinatra ActiveRecord Extension or something similar for managing your applications ActiveRecord connection in a manner similar to the way Rails does. If using the aforementioned Sinatra ActiveRecord Extension, steps for setting up your app with PaperTrail will look something like this:

  1. Add PaperTrail to your Gemfile.

    gem 'paper_trail', '~> 4.0.0'

  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 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.

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)

If you're using the modular Sinatra::Base style of application, you will need to register the extension:

# bleh_app.rbrequire'sinatra/base'classBlehApp < Sinatra::BaseregisterPaperTrail::Sinatraend

Articles

Problems

Please use GitHub's issue tracker.

Contributors

Many thanks to:

Inspirations

Intellectual Property

Copyright (c) 2011 Andy Stewart (boss@airbladesoftware.com). Released under the MIT licence.

About

Track changes to your models' data. Good for auditing or versioning.

Resources

Contributing

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages