Giter Site home page Giter Site logo

paper_trail's Introduction

PaperTrail

Build Status Gem Version SemVer

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

This is the user guide. See also, the API reference.

Choose version: Unreleased, 15.1, 14.0, 13.0, 12.3, 11.1, 10.3, 9.2, 8.1, 7.1, 6.0, 5.2, 4.2, 3.0, 2.7, 1.6

Table of Contents

1. Introduction

1.a. Compatibility

paper_trail ruby activerecord
unreleased >= 3.0.0 >= 6.1, < 7.2
15 >= 3.0.0 >= 6.1, < 7.2
14 >= 2.7.0 >= 6.0, < 7.1
13 >= 2.6.0 >= 5.2, < 7.1
12 >= 2.6.0 >= 5.2, < 7.1
11 >= 2.4.0 >= 5.2, < 6.1
10 >= 2.3.0 >= 4.2, < 6.1
9 >= 2.3.0 >= 4.2, < 5.3
8 >= 2.2.0 >= 4.2, < 5.2
7 >= 2.1.0 >= 4.0, < 5.2
6 >= 1.9.3 >= 4.0, < 5.2
5 >= 1.9.3 >= 3.0, < 5.1
4 >= 1.8.7 >= 3.0, < 5.1
3 >= 1.8.7 >= 3.0, < 5
2 >= 1.8.7 >= 3.0, < 4
1 >= 1.8.7 >= 2.3, < 3

Experts: to install incompatible versions of activerecord, see paper_trail/compatibility.rb.

1.b. Installation

  1. Add PaperTrail to your Gemfile and run bundle.

    gem 'paper_trail'

  2. Add a versions table to your database:

    bundle exec rails generate paper_trail:install [--with-changes] [--uuid]
    bundle exec rails db:migrate
    

    See section 5.c. Generators for details.

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

    class Widget < ActiveRecord::Base
      has_paper_trail
    end
  4. If your controllers have a current_user method, you can easily track who is responsible for changes by adding a controller callback.

    class ApplicationController
      before_action :set_paper_trail_whodunnit
    end

1.c. Basic Usage

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

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

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

v = widget.versions.last
v.event # 'update', 'create', 'destroy'. See also: "The versions.event Column"
v.created_at
v.whodunnit # ID of `current_user`. Requires `set_paper_trail_whodunnit` callback.
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.find 153
widget.name                                 # 'Doobly'

# Add has_paper_trail to Widget model.

widget.versions                             # []
widget.update 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:

Event create update destroy
Model Before nil widget widget
Model After widget widget nil

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

1.d. API Summary

An introductory sample of common features.

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

class Widget < ActiveRecord::Base
  has_paper_trail
end

# Returns this widget's versions.  You can customise the name of the
# association, but overriding this method is not supported.
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.paper_trail.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.paper_trail.version_at(timestamp)

# Returns the widget (not a version) as it was most recently.
widget.paper_trail.previous_version

# Returns the widget (not a version) as it became next.
widget.paper_trail.next_version

And a PaperTrail::Version instance (which is just an ordinary ActiveRecord instance, with all the usual methods) has methods such as:

# Returns the item restored from this version.
version.reify(options = {})

# Return a new item from this version
version.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.terminator
version.whodunnit
version.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

This is just a sample of common features. Keep reading for more.

1.e. Configuration

Many aspects of PaperTrail are configurable for individual models; typically this is achieved by passing options to the has_paper_trail method within a given model.

Some aspects of PaperTrail are configured globally for all models. These settings are assigned directly on the PaperTrail.config object. A common place to put these settings is in a Rails initializer file such as config/initializers/paper_trail.rb or in an environment-specific configuration file such as config/environments/test.rb.

1.e.1 Global

Global configuration options affect all threads.

  • association_reify_error_behaviour
  • enabled
  • has_paper_trail_defaults
  • object_changes_adapter
  • serializer
  • version_limit

Syntax example: (options described in detail later)

# config/initializers/paper_trail.rb
PaperTrail.config.enabled = true
PaperTrail.config.has_paper_trail_defaults = {
  on: %i[create update destroy]
}
PaperTrail.config.version_limit = 3

These options are intended to be set only once, during app initialization (eg. in config/initializers). It is unsafe to change them while the app is running. In contrast, PaperTrail.request has various options that only apply to a single HTTP request and thus are safe to use while the app is running.

2. Limiting What is Versioned, and When

2.a. Choosing Lifecycle Events To Monitor

You can choose which events to track with the on option. For example, if you only want to track update events:

class Article < ActiveRecord::Base
  has_paper_trail on: [:update]
end

has_paper_trail installs callbacks for the specified lifecycle events.

There are four potential callbacks, and the default is to install all four, ie. on: [:create, :destroy, :touch, :update].

The versions.event Column

Your versions table has an event column with three possible values:

event callback
create create
destroy destroy
update touch, update

You may also have the PaperTrail::Version model save a custom string in its event field instead of the typical create, update, destroy. PaperTrail adds an attr_accessor to your model named paper_trail_event, and will insert it, if present, in the event column.

a = Article.create
a.versions.size                           # 1
a.versions.last.event                     # 'create'
a.paper_trail_event = 'update title'
a.update title: 'My Title'
a.versions.size                           # 2
a.versions.last.event                     # 'update title'
a.paper_trail_event = nil
a.update title: 'Alternate'
a.versions.size                           # 3
a.versions.last.event                     # 'update'

Controlling the Order of AR Callbacks

If there are other callbacks in your model, their order relative to those installed by has_paper_trail may matter. If you need to control their order, use the paper_trail_on_* methods.

class Article < ActiveRecord::Base
  # Include PaperTrail, but do not install any callbacks. 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 callback
  paper_trail.on_update     # etc.
  paper_trail.on_create
  paper_trail.on_touch
end

The paper_trail.on_destroy method can be further configured to happen :before or :after the destroy event. Until PaperTrail 4, the default was :after. Starting with PaperTrail 5, the default is :before, to support ActiveRecord 5. (see #683)

2.b. 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:

class Translation < ActiveRecord::Base
  has_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, use attribute_name_was instead of attribute_name.

Saving a New Version Manually

You may want to save a new version regardless of options like :on, :if, or :unless. Or, in rare situations, you may want to save a new version even if the record has not changed.

my_model.paper_trail.save_with_version

2.c. Choosing Attributes To Monitor

Ignore

If you don't want a version created when only a certain attribute changes, you can ignore that attribute:

class Article < ActiveRecord::Base
  has_paper_trail ignore: [:title, :rating]
end

Changes to just the title or rating will not create a version record. Changes to other attributes will create a version record.

a = Article.create
a.versions.length                         # 1
a.update title: 'My Title', rating: 3
a.versions.length                         # 1
a.update title: 'Greeting', content: 'Hello'
a.versions.length                         # 2
a.paper_trail.previous_version.title      # 'My Title'

Note: ignored fields will be stored in the version records. If you want to keep a field out of the versions table, use :skip instead of :ignore; skipped fields are also implicitly ignored.

The :ignore option can also accept Hash arguments that we are considering deprecating.

class Article < ActiveRecord::Base
  has_paper_trail ignore: [:title, { color: proc { |obj| obj.color == "Yellow" } }]
end

Only

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

class Article < ActiveRecord::Base
  has_paper_trail only: [:title]
end

Only changes to the title will create a version record.

a = Article.create
a.versions.length                         # 1
a.update title: 'My Title'
a.versions.length                         # 2
a.update content: 'Hello'
a.versions.length                         # 2
a.paper_trail.previous_version.content    # nil

The :only option can also accept Hash arguments that we are considering deprecating.

class Article < ActiveRecord::Base
  has_paper_trail only: [{ title: Proc.new { |obj| !obj.title.blank? } }]
end

If the title is not blank, then only changes to the title will create a version record.

a = Article.create
a.versions.length                         # 1
a.update content: 'Hello'
a.versions.length                         # 2
a.update title: 'Title One'
a.versions.length                         # 3
a.update content: 'Hai'
a.versions.length                         # 3
a.paper_trail.previous_version.content    # "Hello"
a.update title: 'Title Two'
a.versions.length                         # 4
a.paper_trail.previous_version.content    # "Hai"

Configuring both :ignore and :only is not recommended, but it should work as expected. 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.

Skip

If you never want a field's values in the versions table, you can :skip the attribute. As with :ignore, updates to these attributes will not create a version record. In addition, if a version record is created for some other reason, these attributes will not be persisted.

class Author < ActiveRecord::Base
  has_paper_trail skip: [:social_security_number]
end

Author's social security numbers will never appear in the versions log, and if an author updates only their social security number, it won't create a version record.

Comparing :ignore, :only, and :skip

  • :only is basically the same as :ignore, but its inverse.
  • :ignore controls whether paper_trail will create a version record or not.
  • :skip controls whether paper_trail will save that field with the version record.
  • Skipped fields are also implicitly ignored. paper_trail does this internally.
  • Ignored fields are not implicitly skipped.

So:

  • Ignore a field if you don't want a version record created when it's the only field to change.
  • Skip a field if you don't want it to be saved with any version records.

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

Do not use this in production unless you have a good understanding of threads vs. processes.

A legitimate use case is to speed up tests. See Testing below.

Per HTTP Request

PaperTrail.request(enabled: false) do
  # no versions created
end

or,

PaperTrail.request.enabled = false
# no versions created
PaperTrail.request.enabled = true

Per Class

In the rare case that you need to disable versioning for one model while keeping versioning enabled for other models, use:

PaperTrail.request.disable_model(Banana)
# changes to Banana model do not create versions,
# but eg. changes to Kiwi model do.
PaperTrail.request.enable_model(Banana)
PaperTrail.request.enabled_for_model?(Banana) # => true

This setting, as with all PaperTrail.request settings, affects only the current request, not all threads.

For this rare use case, there is no convenient way to pass a block.

In a Rails Controller Callback (Not Recommended)

PaperTrail installs a callback in your rails controllers. The installed callback will call paper_trail_enabled_for_controller, which you can override.

class ApplicationController < ActionController::Base
  def paper_trail_enabled_for_controller
    # Don't omit `super` without a good reason.
    super && request.user_agent != 'Disable User-Agent'
  end
end

Because you are unable to control the order of callback execution, this technique is not recommended, but is preserved for backwards compatibility.

It would be better to install your own callback and use PaperTrail.request.enabled= as you see fit.

Per Method (Removed)

The widget.paper_trail.without_versioning method was removed in v10, without an exact replacement. To disable versioning, use the Per Class or Per HTTP Request methods.

2.e. 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 limit
PaperTrail.config.version_limit = nil

2.e.1 Per-model limit

Models can override the global PaperTrail.config.version_limit setting.

Example:

# initializer
PaperTrail.config.version_limit = 10

# At most 10 versions
has_paper_trail

# At most 3 versions (2 updates, 1 create). Overrides global version_limit.
has_paper_trail limit: 2

# Infinite versions
has_paper_trail limit: nil

3. Working With Versions

3.a. Reverting And Undeleting A Model

PaperTrail makes reverting to a previous version easy:

widget = Widget.find 42
widget.update name: 'Blah blah'
# Time passes....
widget = widget.paper_trail.previous_version  # the widget as it was before the update
widget.save                                   # reverted

Alternatively you can find the version at a given time:

widget = widget.paper_trail.version_at(1.day.ago)  # the widget as it was one day ago
widget.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.find(42)
widget.destroy
# Time passes....
widget = Widget.new(id:42)    # creating a new object with the same id, re-establishes the link
versions = widget.versions    # versions ordered by versions.created_at, ascending
widget = versions.last.reify  # the widget as it was before destruction
widget.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.

3.b. 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.find 42
live_widget.versions.length                       # 4, for example
widget = live_widget.paper_trail.previous_version # => widget == live_widget.versions.last.reify
widget = widget.paper_trail.previous_version      # => widget == live_widget.versions[-2].reify
widget = widget.paper_trail.next_version          # => widget == live_widget.versions.last.reify
widget.paper_trail.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.find 42
version = widget.versions[-2]    # assuming widget has several versions
previous_version = version.previous
next_version = 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.last
widget = latest_version.reify
widget.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.find 42
widget.paper_trail.live?            # true
widget = widget.paper_trail.previous_version
widget.paper_trail.live?            # false

See also: Section 3.e. Queries

3.c. 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 column to your versions table, PaperTrail will store the changes diff in each version. Ignored attributes are omitted.

widget = Widget.create name: 'Bob'
widget.versions.last.changeset # reads object_changes column
# {
#   "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 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.destroy
widget.versions.last.changeset
# {}

Prior to 10.0.0, the object_changes were only stored for create and update events. As of 10.0.0, they are stored for all three events.

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

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.

Unfortunately, there is no currently widely available and supported library for diffing two ActiveRecord objects.

3.d. 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> delete from versions where created_at < '2010-06-01';
PaperTrail::Version.where('created_at < ?', 1.day.ago).delete_all

3.e. Queries

You can query records in the versions table based on their object or object_changes columns.

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

# Find versions before and after attribute `atr` had value `v`:
PaperTrail::Version.where_object_changes(atr: 'v')

See also:

  • where_object_changes_from
  • where_object_changes_to
  • where_attribute_changes

Only where_object supports text columns. Your object_changes column should be a json or jsonb column if possible. If you must use a text column, you'll have to write a custom object_changes_adapter.

3.f. Defunct item_ids

The item_ids in your versions table can become defunct over time, potentially causing application errors when ids in the foreign table are reused. id reuse can be an explicit choice of the application, or implicitly caused by sequence cycling. The chance of id reuse is reduced (but not eliminated) with bigint ids or uuids, no cycle sequences, and/or when versions are periodically deleted.

Ideally, a Foreign Key Constraint (FKC) would set item_id to null when an item is deleted. However, items is a polymorphic relationship. A partial FKC (e.g. an FKC with a where clause) is possible, but only in Postgres, and it is impractical to maintain FKCs for every versioned table unless the number of such tables is very small.

If per-table Version classes are used, then a partial FKC is no longer needed. So, a normal FKC can be written in any RDBMS, but it remains impractical to maintain so many FKCs.

Some applications choose to handle this problem by "soft-deleting" versioned records, i.e. marking them as deleted instead of actually deleting them. This completely prevents id reuse, but adds complexity to the application. In most applications, this is the only known practical solution to the id reuse problem.

4. Saving More Information About Versions

4.a. Finding Out Who Was Responsible For A Change

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

PaperTrail.request.whodunnit = 'Andy Stewart'
widget.update name: 'Wibble'
widget.versions.last.whodunnit # Andy Stewart

Setting whodunnit to a Proc

whodunnit= also accepts a Proc, in the rare case that lazy evaluation is required.

PaperTrail.request.whodunnit = proc do
  caller.find { |c| c.starts_with? Rails.root.to_s }
end

Because lazy evaluation can be hard to troubleshoot, this is not recommended for common use.

Setting whodunnit Temporarily

To set whodunnit temporarily, for the duration of a block, use PaperTrail.request:

PaperTrail.request(whodunnit: 'Dorian Marié') do
  widget.update name: 'Wibble'
end

Setting whodunnit with a controller callback

If your controller has a current_user method, PaperTrail provides a callback that will assign current_user.id to whodunnit.

class ApplicationController
  before_action :set_paper_trail_whodunnit
end

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:

class ApplicationController
  def user_for_paper_trail
    logged_in? ? current_member.id : 'Public user'  # or whatever
  end
end

See also: Setting whodunnit in the rails console

Terminator and Originator

A version's whodunnit column tells us 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 tells us 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.find 153                    # assume widget has 0 versions
PaperTrail.request.whodunnit = 'Alice'
widget.update name: 'Yankee'
widget.paper_trail.originator               # 'Alice'
PaperTrail.request.whodunnit = 'Bob'
widget.update name: 'Zulu'
widget.paper_trail.originator               # 'Bob'
first_version, last_version = widget.versions.first, widget.versions.last
first_version.whodunnit                     # 'Alice'
first_version.paper_trail_originator        # nil
first_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.

4.b. Associations

To track and reify associations, use paper_trail-association_tracking (PT-AT).

From 2014 to 2018, association tracking was an experimental feature, but many issues were discovered. To attract new volunteers to address these issues, PT-AT was extracted (see #1070).

Even though it had always been an experimental feature, we didn't want the extraction of PT-AT to be a breaking change, so great care was taken to remove it slowly.

  • In PT 9, PT-AT was kept as a runtime dependency.
  • In PT 10, it became a development dependency (If you use it you must add it to your own Gemfile) and we kept running all of its tests.
  • In PT 11, it will no longer be a development dependency, and it is responsible for its own tests.

4.b.1 The optional item_subtype column

As of PT 10, users may add an item_subtype column to their versions table. When storing versions for STI models, rails stores the base class in item_type (that's just how polymorphic associations like item work) In addition, PT will now store the subclass in item_subtype. If this column is present PT-AT will use it to fix a rare issue with reification of STI subclasses.

add_column :versions, :item_subtype, :string, null: true

So, if you use PT-AT and STI, the addition of this column is recommended.

4.c. Storing Metadata

You can add your own custom columns to your versions table. Values can be given using Model Metadata or Controller Metadata.

Model Metadata

You can specify metadata in the model using has_paper_trail(meta:).

class Article < ActiveRecord::Base
  belongs_to :author
  has_paper_trail(
    meta: {
      author_id: :author_id, # model attribute
      word_count: :count_words, # arbitrary model method
      answer: 42, # scalar value
      editor: proc { |article| article.editor.full_name } # a Proc
    }
  )
  def count_words
    153
  end
end

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.

class ApplicationController
  def info_for_paper_trail
    { ip: request.remote_ip, user_agent: request.user_agent }
  end
end

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 can Override PaperTrail Columns

Experts only. Metadata will override the normal values that PT would have inserted into its own columns.

PT Column How bad of an idea? Alternative
created_at forbidden*
event meh paper_trail_event
id forbidden
item_id forbidden
item_subtype forbidden
item_type forbidden
object a little dangerous
object_changes a little dangerous
updated_at forbidden
whodunnit meh PaperTrail.request.whodunnit=

* forbidden - raises a PaperTrail::InvalidOption error as of PT 14

5. ActiveRecord

5.a. Single Table Inheritance (STI)

PaperTrail supports Single Table Inheritance, and even supports an un-versioned base model, as of 23ffbdc7e1.

class Fruit < ActiveRecord::Base
  # un-versioned base model
end
class Banana < Fruit
  has_paper_trail
end

However, there is a known issue when reifying associations, see #594

5.b. Configuring the versions Association

5.b.1. versions association

You may configure the name of the versions association by passing a different name (default is :versions) in the versions: options hash:

class Post < ActiveRecord::Base
  has_paper_trail versions: {
    name: :drafts
  }
end

Post.new.versions # => NoMethodError

You may pass a scope to the versions association with the scope: option:

class Post < ActiveRecord::Base
  has_paper_trail versions: {
    scope: -> { order("id desc") }
  }

  # Equivalent to:
  has_many :versions,
    -> { order("id desc") },
    class_name: 'PaperTrail::Version',
    as: :item
end

Any other options supported by has_many can be passed along to the has_many macro via the versions: options hash.

class Post < ActiveRecord::Base
  has_paper_trail versions: {
    extend: VersionsExtensions,
    autosave: false
  }
end

Overriding (instead of configuring) the versions method is not supported. Overriding associations is not recommended in general.

5.b.2. item association

A PaperTrail::Version object belongs_to an item, the relevant record.

The item association is first defined in PaperTrail::VersionConcern, but associations can be redefined.

Example: adding a counter_cache to item association
# app/models/paper_trail/version.rb
module PaperTrail
  class Version < ActiveRecord::Base
    belongs_to :item, polymorphic: true, counter_cache: true
  end
end

When redefining an association, its options are replaced not merged, so don't forget to specify the options from PaperTrail::VersionConcern, like polymorphic.

Be advised that redefining an association is an undocumented feature of Rails.

5.c. Generators

PaperTrail has one generator, paper_trail:install. It writes, but does not run, a migration file. The migration creates the versions table.

Reference

The most up-to-date documentation for this generator can be found by running rails generate paper_trail:install --help, but a copy is included here for convenience.

Usage:
  rails generate paper_trail:install [options]

Options:
  [--with-changes], [--no-with-changes]            # Store changeset (diff) with each version
  [--uuid]                                         # To use paper_trail with projects using uuid for id

Runtime options:
  -f, [--force]                    # Overwrite files that already exist
  -p, [--pretend], [--no-pretend]  # Run but do not make any changes
  -q, [--quiet], [--no-quiet]      # Suppress status output
  -s, [--skip], [--no-skip]        # Skip files that already exist

Generates (but does not run) a migration to add a versions table.

5.d. Protected Attributes

As of version 6, PT no longer supports rails 3 or the protected_attributes gem. If you are still using them, you may use PT 5 or lower. We recommend upgrading to strong_parameters as soon as possible.

If you must use protected_attributes for now, and want to use PT > 5, you can reopen PaperTrail::Version and add the following attr_accessible fields:

# app/models/paper_trail/version.rb
module PaperTrail
  class Version < ActiveRecord::Base
    include PaperTrail::VersionConcern
    attr_accessible :item_type, :item_id, :event, :whodunnit, :object, :object_changes, :created_at
  end
end

This unsupported workaround has been tested with protected_attributes 1.0.9 / rails 4.2.8 / paper_trail 7.0.3.

6. Extensibility

6.a. Custom Version Classes

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

class PostVersion < PaperTrail::Version
  # custom behaviour, e.g:
  self.table_name = :post_versions
end

class Post < ActiveRecord::Base
  has_paper_trail versions: {
    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:

class PostVersion < PaperTrail::Version
  self.table_name = :post_versions
  self.sequence_name = :post_versions_id_seq
end

If you only use custom version classes and don't have a versions table, you must let ActiveRecord know that your base version class (eg. ApplicationVersion below) class is an abstract_class.

# app/models/application_version.rb
class ApplicationVersion < ActiveRecord::Base
  include PaperTrail::VersionConcern
  self.abstract_class = true
end

class PostVersion < ApplicationVersion
  self.table_name = :post_versions
  self.sequence_name = :post_versions_id_seq
end

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:

class Post < ActiveRecord::Base
  has_paper_trail versions: { name: :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

6.b. 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 :versions do |t|
  # ...
  t.json :object          # Full object changes
  t.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, :new_object, :jsonb # or :json
# add_column :versions, :new_object_changes, :jsonb # or :json

# PaperTrail::Version.reset_column_information # needed for rails < 6

PaperTrail::Version.where.not(object: nil).find_each do |version|
  version.update_column(:new_object, YAML.load(version.object))

  # if version.object_changes
  #   version.update_column(
  #     :new_object_changes,
  #     YAML.load(version.object_changes)
  #   )
  # end
end

remove_column :versions, :object
# remove_column :versions, :object_changes
rename_column :versions, :new_object, :object
# rename_column :versions, :new_object_changes, :object_changes

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_object
add_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_each do |version|
  version.update_columns old_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:

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

Using ActiveRecord:

class ConvertVersionsObjectToJson < ActiveRecord::Migration
  def up
    change_column :versions, :object, 'jsonb USING object::jsonb'
  end

  def down
    change_column :versions, :object, 'text USING object::text'
  end
end

6.c. Custom Object Changes

To fully control the contents of their object_changes column, expert users can write an adapter.

PaperTrail.config.object_changes_adapter = MyObjectChangesAdapter.new

class MyObjectChangesAdapter
  # @param changes Hash
  # @return Hash
  def diff(changes)
    # ...
  end
end

You should only use this feature if you are comfortable reading PT's source to see exactly how the adapter is used. For example, see how diff is used by reading ::PaperTrail::Events::Base#recordable_object_changes.

An adapter can implement any or all of the following methods:

  1. diff: Returns the changeset in the desired format given the changeset in the original format
  2. load_changeset: Returns the changeset for a given version object
  3. where_object_changes: Returns the records resulting from the given hash of attributes.
  4. where_object_changes_from: Returns the records resulting from the given hash of attributes where the attributes changed from the provided value(s).
  5. where_object_changes_to: Returns the records resulting from the given hash of attributes where the attributes changed to the provided value(s).
  6. where_attribute_changes: Returns the records where the attribute changed to or from any value.

Depending on your needs, you may choose to implement only a subset of these methods.

Known Adapters

6.d. Excluding the Object Column

The object column ends up storing a lot of duplicate data if you have models that have many columns, and that are updated many times. You can save ~50% of storage space by removing the column from the versions table. It's important to note that this will disable reify and where_object.

7. Testing

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

7.a. Minitest

First, disable PT for the entire ruby process.

# in config/environments/test.rb
config.after_initialize do
  PaperTrail.enabled = false
end

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

# in test/test_helper.rb
def with_versioning
  was_enabled = PaperTrail.enabled?
  was_enabled_for_request = PaperTrail.request.enabled?
  PaperTrail.enabled = true
  PaperTrail.request.enabled = true
  begin
    yield
  ensure
    PaperTrail.enabled = was_enabled
    PaperTrail.request.enabled = was_enabled_for_request
  end
end

Then, use the helper in your tests.

test 'something that needs versioning' do
  with_versioning do
    # your test
  end
end

7.b. 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.rb
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.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' do
  it 'by default, PaperTrail will be turned off' do
    expect(PaperTrail).to_not be_enabled
  end

  with_versioning do
    it 'within a `with_versioning` block it will be turned on' do
      expect(PaperTrail).to be_enabled
    end
  end

  it 'can be turned on at the `it` or `describe` level', versioning: true do
    expect(PaperTrail).to be_enabled
  end
end

The helper will also reset whodunnit 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.request.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:

class Widget < ActiveRecord::Base
end

describe Widget do
  it 'is not versioned by default' do
    is_expected.to_not be_versioned
  end

  describe 'add versioning to the `Widget` class' do
    before(:all) do
      class Widget < ActiveRecord::Base
        has_paper_trail
      end
    end

    it 'enables paper trail' do
      is_expected.to be_versioned
    end
  end
end

Matchers

The have_a_version_with matcher makes assertions about versions using where_object, based on the object column.

describe '`have_a_version_with` matcher' do
  it 'is possible to do assertions on version attributes' do
    widget.update!(name: 'Leonard', an_integer: 1)
    widget.update!(name: 'Tom')
    widget.update!(name: 'Bob')
    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

The have_a_version_with_changes matcher makes assertions about versions using where_object_changes, based on the optional object_changes column.

describe '`have_a_version_with_changes` matcher' do
  it 'is possible to do assertions on version changes' do
    widget.update!(name: 'Leonard', an_integer: 1)
    widget.update!(name: 'Tom')
    widget.update!(name: 'Bob')
    expect(widget).to have_a_version_with_changes name: 'Leonard', an_integer: 2
    expect(widget).to have_a_version_with_changes an_integer: 2
    expect(widget).to have_a_version_with_changes name: 'Bob'
  end
end

For more examples of the RSpec matchers, see the Widget spec

7.c. Cucumber

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

# 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. When you want 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/ do
  with_versioning do
    # PaperTrail will be turned on for all code inside of this block
  end
end

The helper will also reset the 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.request.controller_info value to {} as well, again, to help prevent data spillover between tests.

7.d. Spork

If you want 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.rb

require 'spork'

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

7.e. Zeus or Spring

If you want 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.rb

ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'paper_trail/frameworks/rspec'

8. PaperTrail Plugins

  • paper_trail-active_record
  • paper_trail-association_tracking - track and reify associations
  • paper_trail-audit
  • paper_trail-background
  • paper_trail-globalid - enhances whodunnit by adding an actor
  • paper_trail-hashdiff
  • paper_trail-rails
  • paper_trail-related_changes
  • paper_trail-sinatra
  • paper_trail_actor
  • paper_trail_changes
  • paper_trail_manager
  • paper_trail_scrapbook
  • paper_trail_ui
  • revertible_paper_trail
  • rspec-paper_trail
  • sequel_paper_trail

9. Integration with Other Libraries

10. Related Libraries and Ports

Articles

Problems

Please use GitHub's issue tracker.

Contributors

Created by Andy Stewart in 2010, maintained since 2012 by Ben Atkins, since 2015 by Jared Beck, with contributions by over 150 people.

https://github.com/paper-trail-gem/paper_trail/graphs/contributors

Contributing

See our contribution guidelines

Inspirations

Intellectual Property

Copyright (c) 2011 Andy Stewart ([email protected]). Released under the MIT licence.

paper_trail's People

Contributors

airblade avatar aried3r avatar batter avatar benzittlau avatar bradleypriest avatar budu avatar dwbutler avatar edtsech avatar emmanuel avatar jaredbeck avatar jhoglund avatar lyfeyaj avatar magni- avatar magnusvk avatar mattmacleod avatar md5 avatar mhuggins avatar michaelkhabarov avatar mikeraimondi avatar moserrya avatar owenr avatar rposborne avatar seanlinsley avatar seanmarcia avatar sgrif avatar tlynam avatar tylerrick avatar westonganger avatar zacheryph avatar znz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

paper_trail's Issues

Updates don't save in rails 3 beta 3

I'm using Rails 3 beta 3 and when I update a record the record doesn't actually get saved, but a version does get created. If I remove has_paper_trail from the model then records update like normal. I'm not sure what has changed in Rails 3 that might be causing this. Any ideas?

Also, the generator doesn't work but it was easy enough to grab it from the source.

Issues on production server

The gem (2.0.1) in rails (3.0.4) is working great in development. It also works fine in production on the server except for delete/destroy, which gives the following:

ActiveRecord::StatementInvalid (Mysql2::Error: Column 'item_type' cannot be null: INSERT INTO versions (created_at, event, object, whodunnit, item_type, item_id) VALUES ('2011-03-08 04:46:01', 'destroy', '--- \nfamily_id: \ncomment:...

I am happy to track down what is causing the issue if you can give me some direction.

Thanks,

Ed.

Unable to Generate Migration in Rails3

In Rails3 "script/generate ..." was replaced by "rails generate ..." which expects to find Rails3 generators. When trying to generate the paper_trail migration I get an error like such:

$ rails generate paper_trail
Could not find generator paper_trail.

paper_trail does not honor set_inheritance_column

Hi, my model has a column 'type' in the database. Therefor I have to tell activerecord it should use some other attribute than 'type' for whatever it wants to do with it.

It seems your plugin doesn't honor the set_inheritance_column and still does like to do something with type. My inheritance_column is changed to 'ruby-type'.

I have patched your version.rb to first check the existance of the attribute 'ruby-type' before it tries 'type'.
I know it really sucks, but might be useful to you :-)
Here is the patch:

55,63c55,56
<       tole_types = ['ruby_type', 'type']
<       begin
<         tole_type = tole_types.shift
<             class_name = attrs[tole_type].blank? ? item_type : attrs[tole_type]
<             klass = class_name.constantize
<       rescue Exception => e
<         retry if tole_types.length > 0
<       end
<                   

---
>         class_name = attrs['type'].blank? ? item_type : attrs['type']
>         klass = class_name.constantize

Anyways: thank you very much for the very nice plugin!

accepted_nested_attributes_for throws undefined method on model.update for nested models

I have a User model that has an association of answers. When I add has_paper_trail to the User model and do an update (PUT) with a nested model I get this error:

NoMethodError (undefined method `answers_attributes' for #):
  /usr/local/lib/jruby-1.4.0/lib/ruby/gems/1.8/gems/paper_trail-1.4.0/lib/paper_trail/has_paper_trail.rb:78:in `previous_version'
  /usr/local/lib/jruby-1.4.0/lib/ruby/gems/1.8/gems/paper_trail-1.4.0/lib/paper_trail/has_paper_trail.rb:52:in `record_update'
  app/models/user.rb:414:in `update_with_ldap'
  app/controllers/users_controller.rb:68:in `update'
  app/controllers/users_controller.rb:67:in `update'
  haml (2.2.16) lib/sass/plugin/rails.rb:19:in `process'
  /usr/local/lib/jruby-1.4.0/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
  /usr/local/lib/jruby-1.4.0/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
  /usr/local/lib/jruby-1.4.0/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
  /usr/local/lib/jruby-1.4.0/lib/ruby/1.8/webrick/server.rb:162:in `start'
  /usr/local/lib/jruby-1.4.0/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
  /usr/local/lib/jruby-1.4.0/lib/ruby/1.8/webrick/server.rb:95:in `start'
  /usr/local/lib/jruby-1.4.0/lib/ruby/1.8/webrick/server.rb:92:in `each'
  /usr/local/lib/jruby-1.4.0/lib/ruby/1.8/webrick/server.rb:92:in `start'
  /usr/local/lib/jruby-1.4.0/lib/ruby/1.8/webrick/server.rb:23:in `start'
  /usr/local/lib/jruby-1.4.0/lib/ruby/1.8/webrick/server.rb:82:in `start'

When I remove has_paper_trail the update succeeds.

Temporarily I have monkey-patched the previous_version method with a begin/rescue.

paper_trail.rb Line 78:

      begin
        changes.each do |attr, ary|
          previous.send "#{attr}=", ary.first
        end
      rescue 
        RAILS_DEFAULT_LOGGER.error('previous version error')
      end

My Model looks like this:

Class User < ActiveRecord::Base
  has_paper_trail
  has_many :answers
  accepts_nested_attributes_for :answers, :allow_destroy => true

Any ideas on how to resolve this?

Notes:

  1. I am using JRuby 1.4.0 (Ruby 1.8.7 patch level 174) and have not tried this with regular Ruby.
  2. Rails 2.3.5

Versions don't have the :object set when testing with rspec

I am using Rspec to test.

This is some code from my test.

it "should be able to render an older versions" do
    my_model = MyModel.create(:body => 'some text')
    my_model.update_attributes(:body => "Some new text")
     get :show, :id => my_model.id, :v => 1
    response.should render_template(:show)
end

It fails because the Version that gets created has nil for the object.
<Version id: 217, item_type: "MyModel", item_id: 178, event: "create", whodunnit: "1079", object: nil, created_at: "2011-03-30 20:34:17">

Original gets overwriten if column is a serialized Array

Your plugin is working great except for one issue, I have a serialized Array stored inside a model that is being versioned, and any changes done to the Array seems to be going through, when I call model.save or model.update_attribute :Array_column, the original data entry seems to be updated, thus loosing the original data, which is a critical issue in my case. Please help

ArgumentError with reify

I received the following error when attempting to revert an update:

ArgumentError: syntax error on line 0, col 37: --- \nreferred_by: Blah\noccupation: !str \n str: electrician\n "@_rails_html_safe": false\nname: !str \n str: Abbey Streich\n "@_rails_html_safe": false\nfax_number: !str \n str: 978.631.7298 x05457\n "@_rails_html_safe": false\ncity: !str \n str: Ipoh\n "@_rails_html_safe": false\naddress: !str \n str: 3855 Brekke Bypass\n "@_rails_html_safe": false\nzip: !str \n str: "61851"\n "@_rails_html_safe": false\nphoto_file_size: 74095\ncreated_at: 2009-12-28 23:02:18 Z\nupdated_at: 2010-01-05 14:58:11 Z\nphoto_file_name: OldWoman.jpg\noutpatient: true\nnotes: !str \n str: ""\n "@_rails_html_safe": false\nphoto_content_type: image/jpeg\nid: 54\nuser_id: \nphoto_updated_at: 2009-12-28 15:04:52 Z\nphone_number: !str \n str: 732.727.0168 x9825\n "@_rails_html_safe": false\nmale: false\nbirthday: 1889-01-05\nstatus: \nstate: !str \n str: Kuala Lumpur\n "@_rails_html_safe": false\nrace: !str \n str: Indian\n "@_rails_html_safe": false\n' from /usr/local/lib/ruby/1.8/yaml.rb:133:inload'
from /usr/local/lib/ruby/1.8/yaml.rb:133:in load' from /usr/local/lib/ruby/gems/1.8/gems/paper_trail-1.3.1/lib/paper_trail/version.rb:9:inreify'
from (irb):4
from :0

paper_trail saves attributes that came from a join and select

Hi,

I am doing a query like:
Episode.select('episodes.*, shows.name as show_name).joins(:show)
When paper_trail kicks in before the update, it will save the show_name in the serialized object:
---
created_at: 2011-03-12 14:48:30 Z
episode: S01E08
epnum: 8
id: 13368
prodnum: ""
season: 1
show_id: 1234
show_name:
title: Wine Pairing
updated_at: 2011-03-12 14:00:06 Z

paper_trail thinks that show_name is an attribute of episode, which it isn't in real life. Only for this join.
paper_trail should only save attributes that are native to the model.

protected attributes

i use this for default protection:

class ActiveRecord::Base
  attr_accessible
  attr_accessor :accessible

  private

  def mass_assignment_authorizer
    if accessible == :all
      self.class.protected_attributes
    else
      super + (accessible || [])
    end
  end
end

i gave has_paper_trail to some model and update gives this

$ tail -f log/development.log | grep WARNING
WARNING: Can't mass-assign protected attributes: event, object, whodunnit

and versions table remains empty

STI

i got Post < AR and NewsPost < Post models
Versions with event create and update are stored as Post versions
and delete event has item_type set to NewsPost
that produces an eroor in logic - i cannot see, say, Version.find(34).next, because next version got different item_type

Version Lists

I'm trying to create a list of restore-able versions for a template model. If you change the template, you are required to provide a "version description" that describes what you changed in the template. However, since paper trail stores the version before the changes, my version list ends up being incorrect. The version description doesn't match the actual changes for the version record. Is there a way around this, or maybe a better solution?

Thanks in advance. I've used paper trail for other projects, and it's a huge time saver. Keep up the good work!

class Template < ActiveRecord::Base
  has_paper_trail :ignore => :title, :meta => { :version_description => Proc.new { |template| template.version_description } }
  validates :version_description, :presence => true, :if => Proc.new { |template| template.code_changed? }, :on => :update
  attr_accessor :version_description
end

Here is where I'm iterating through each version in my view. I'd like to display the version description corresponding to the actual change. So that when you view the list, and it says something like "added X feature", and you click restore, it will return to when that feature was first added.

<% @template.versions.reverse.each_with_index do |version, i| %>
  <tr class="gradeX">
    <td style="text-align:left; padding-left:10px;"><%= version.created_at.to_i %></td>
    <td style="text-align:left;"><span rel="tooltip" title="<%= version.version_description %>" style="cursor:help;"><%= truncate(version.version_description, :length => 50) %></span></td>
    <td><%= time_ago_in_words(version.created_at) %> ago</td>
    <td><%= link_to "Restore this version", admin_revert_version_path(version), :method => :post %></td>
  </tr>
<% end %>

current version on model

Hey,

This is a feature request. I want to get the actual version_id on the model like the versions attribute. I tried to add this myself but I don't got it working. Maybe I am a little to new to ruby and rails.

Nice work and please keep it up!

Unable to Create paper_trail Migration in Rails 3

In rails 3 "script/generate ..." was replaced by "rails generate ..." which expects to find rails 3 generators. When trying to generate the paper_trail migration I get an error like such:

$ rails generate paper_trail
Could not find generator paper_trail.

I should add that copying the migration over from rails 2.3.8 works without a problem. Therefore this is an issue for new rails 3 projects and not for migrated ones.

is_switched_on? is always false

Starting using paper_trail I never got the version saved in versions table. Debugghing I noticed that the after_create event is correctly triggered but the is_switched_on? is false.
I tried to call MyModelWith-has_paper_trail.paper_trail_on but nothing changed.

unable to delete

ruby-1.9.2-p180 :009 > Post.find(213237).destroy
ActiveRecord::StatementInvalid: PGError: ERROR: null value in column "item_type" violates not-null constraint
: INSERT INTO "versions" ("item_type", "item_id", "event", "whodunnit", "object", "created_at") VALUES (NULL, NULL, 'destroy', NULL, '---
album_id: !!null
annotation: ''''
author_email: ''''
author_id: !!null
author_name: ''''
authorship: !!null
commentable: false
created_at: 2010-10-15 12:02:05.569545000Z
creator_id: !!null
exclude_from_rss: false
genre: none
id: 213237
image_author: !!null
image_description: !!null
image_title: !!null
links: !!null
locked_by: !!null
main_in_rubric_from: !!null
main_on_site_from: !!null
name: тест
old_id: !!null
post_image_content_type: !!null
post_image_file_name: !!null
post_image_file_size: !!null
post_image_updated_at: !!null
published_at: 2010-10-15 12:02:05.000000000Z
region_id: !!null
rubric_id: 67
source: ''''
source_url: ''''
storyline_id: 0
text: ''''
thread_id: !!null
type: PersonPost
updated_at: 2010-10-15 13:12:38.924255000Z
updater_id: !!null
video_id: !!null
views_count: 0
visibility: true
weight: 5
', '2011-07-06 08:47:10.938480') RETURNING "id"
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/connection_adapters/abstract_adapter.rb:207:in rescue in log' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/connection_adapters/abstract_adapter.rb:199:inlog'
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/connection_adapters/postgresql_adapter.rb:514:in execute' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/connection_adapters/postgresql_adapter.rb:1004:inselect_raw'
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/connection_adapters/postgresql_adapter.rb:997:in select' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/connection_adapters/abstract/database_statements.rb:7:inselect_all'
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/connection_adapters/abstract/query_cache.rb:56:in select_all' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/connection_adapters/abstract/database_statements.rb:13:inselect_one'
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/connection_adapters/abstract/database_statements.rb:19:in select_value' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/connection_adapters/postgresql_adapter.rb:433:ininsert'
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/arel-2.0.10/lib/arel/select_manager.rb:217:in insert' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/relation.rb:14:ininsert'
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/persistence.rb:274:in create' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/timestamp.rb:47:increate'
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/callbacks.rb:277:in block in create' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.0.9/lib/active_support/callbacks.rb:419:in_run_create_callbacks'
... 16 levels...
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/base.rb:504:in create' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/paper_trail-2.2.5/lib/paper_trail/has_paper_trail.rb:119:inrecord_destroy'
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.0.9/lib/active_support/callbacks.rb:441:in _run_destroy_callbacks' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/callbacks.rb:256:indestroy'
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/transactions.rb:235:in block in destroy' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/transactions.rb:292:inblock in with_transaction_returning_status'
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/connection_adapters/abstract/database_statements.rb:139:in transaction' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/transactions.rb:207:intransaction'
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/transactions.rb:290:in with_transaction_returning_status' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.9/lib/active_record/transactions.rb:235:indestroy'
from (irb):9
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.9/lib/rails/commands/console.rb:44:in start' from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.9/lib/rails/commands/console.rb:8:instart'
from /home/nir0/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.9/lib/rails/commands.rb:23:in <top (required)>' from script/rails:6:inrequire'
from script/rails:6:in `

'

Install instructions need a slight tweak

If you execute the suggested:

bundle exec rails generate paper_trail:install

You'll get an error. Changing it to...

bundle exec rails generate paper_trail

... seems to do the trick.

Duplicate versions created for the same operation

We are having a problem in production where paper trail is creating duplicate version objects, literally only milliseconds apart but otherwise identical, for some operations. What's weird is that I have not been able to reproduce this in development. Have you heard of any problems like this? We're using paper trail 1.1.2 btw.

reify should default to :has_one => false

This may be somewhat opinionated, but I feel strongly about this. I think that PaperTrail's reify method should default the :has_one argument to false, and allow this to be enabled and disabled globally. Having to always add :has_one => false shouldn't be necessary. Given that has_one associations are currently the only associations PaperTrail supports, it should really only be enabled when required.

I have also had mixed results when reifying has_one associations, and found that in some situations (which I am still looking into and will post here when I know more about them), reifying has_one's can inadvertently remove the association permanently (not deleting the record, but setting the foreign_key to nil).

As such, I'd be interested to see whether it would be more worthwhile to add a global config option for has_one support and for this to be set to false by default. Happy to submit a pull request with this functionality if people support the change.

Cheers :)

Feature Request: creating future versions with out updating model

The problem I have is that I want to let my users update specific models but I want to approve their changes. So what I was thinking of is a feature where you could create a new version with out actually changing the model. Then later on I could move the versions forward if I want.

I'd possibly be interested in coding this myself with some guidance if the patch will be accepted.

"TypeError: can't convert String into Hash" Rails 3.07 / Ruby 1.92p180

Hello,

when my via scaffold created test - trying to save a new object, the test failed.


test_should_create_budgetgroup(BudgetgroupsControllerTest):
TypeError: can't convert String into Hash
C:/Ruby192/lib/ruby/gems/1.9.1/gems/paper_trail-2.2.5/lib/paper_trail/has_paper_trail.rb:142:in merge' C:/Ruby192/lib/ruby/gems/1.9.1/gems/paper_trail-2.2.5/lib/paper_trail/has_paper_trail.rb:142:inmerge_metadata'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/paper_trail-2.2.5/lib/paper_trail/has_paper_trail.rb:106:in record_create' C:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.7/lib/active_support/callbacks.rb:419:in_run_create_callbacks'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/callbacks.rb:277:in create' C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/persistence.rb:246:increate_or_update'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/callbacks.rb:273:in block in create_or_update' C:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.7/lib/active_support/callbacks.rb:419:in_run_save_callbacks'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/callbacks.rb:273:in create_or_update' C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/persistence.rb:39:insave'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/validations.rb:43:in save' C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/attribute_methods/dirty.rb:21:insave'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/transactions.rb:240:in block (2 levels) in save' C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/transactions.rb:292:inblock in with_transaction_returning_status'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/connection_adapters/abstract/database_statements.rb:139:in transaction' C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/transactions.rb:207:intransaction'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/transactions.rb:290:in with_transaction_returning_status' C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/transactions.rb:240:inblock in save'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/transactions.rb:251:in rollback_active_record_state!' C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.7/lib/active_record/transactions.rb:239:insave'

C:/source/MPIStipend/trunk/MPIStipend/app/controllers/budgetgroups_controller.rb:47:in `block in create'

htmldiff and escaping HTML differences between current and reified versions

I've been having problems when comparing a version (reified) vs the current record. I thought simply using CGI.unescapeHTML() on the versions would save me, but it still leaves lots of spaces and things which are different from the current record.

current record

  • We've loved you for many years

reified version

  • \n\tWe#39;ve loved you for many years

unescaping reified version

  • \n\tWe've loved you for many years

is there a way around this so HTMLDiff doesn't cause a fit?

Can I ignore changes in certain fields?

My model has one field that change every month. It's a depreciation value cache. But I want to ignore any change in this field (don't create a version). Is it possible? If not, I'm considering to create an class method setting paper_trail_off, changing and then paper_trail_on. Maybe that's the right way to do it. Any ideas?

Maybe implement a feature that allows us to pass those setting to has_paper_trail?

ps: thanks for the awesome gem

ActiveRecord::RecordNotSaved exception on destroy with Rails 3.0.2

When you destroy a model in Rails 3.0.2 you get an Exception thrown (ActiveRecord::RecordNotSaved)

To fix this I don't use the versions.create method, instead I use the Version.create method with the "item" attribute.

By the way, great job with this gem, is a very usefull one.

Removed hardcoded primary key from versions

Would it not be benefical to remove the hardcoded id columns from library.

eg. id => #{self.primary_key}

Then it could be used with app using non standard ID columns e.g. UUID columns

Failed generating migration file: `require': no such file to load -- rails/generators/active_record/migration (LoadError)

I am trying to add paper_trail to my Rails 3 project for the first time, but am getting an error. I have taken the following steps:

First, I added paper_trail to my Gemfile like so:

gem 'paper_trail', '~> 2'

Then I ran bundle install, which installed the paper_trail gem. Then I tried generating the migration file with this command:

bundle exec rails generate paper_trail:install

...but it failed with this stack trace:

/Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:239:in `require': no such file to load -- rails/generators/active_record/migration (LoadError)
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:239:in `block in require'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:225:in `block in load_dependency'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:591:in `new_constants_in'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:225:in `load_dependency'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:239:in `require'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/paper_trail-2.2.4/lib/generators/paper_trail/install_generator.rb:3:in `<top (required)>'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:239:in `require'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:239:in `block in require'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:225:in `block in load_dependency'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:591:in `new_constants_in'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:225:in `load_dependency'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:239:in `require'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.0/lib/rails/generators.rb:286:in `block (2 levels) in lookup'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.0/lib/rails/generators.rb:282:in `each'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.0/lib/rails/generators.rb:282:in `block in lookup'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.0/lib/rails/generators.rb:281:in `each'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.0/lib/rails/generators.rb:281:in `lookup'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.0/lib/rails/generators.rb:141:in `find_by_namespace'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.0/lib/rails/generators.rb:161:in `invoke'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.0/lib/rails/commands/generate.rb:10:in `<top (required)>'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:239:in `require'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:239:in `block in require'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:225:in `block in load_dependency'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:591:in `new_constants_in'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:225:in `load_dependency'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:239:in `require'
    from /Users/andrew/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.0/lib/rails/commands.rb:17:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

What should I do?

See all changes by User

Is there a way to see all of the changes made by a particular user to all of the models being watched?

Object: nil for the 'create' version

I'm getting a nil object on every create event.
Is this the desired behavior?

This gives a problem when the item is deleted, and you want to verify the first version with reify.

Skip versioning on create?

Does this gem allow you to set it to skip versioning on creation? I've looked at the docs and code and I can't see an option anywhere

paper_trail breaks up with Globalize3

More just a info, than a actual issue. Globalize keeps translated fields in separate table. At this moment paper_trails prevents Globalize3 from working. Translated field isn't update when model has_paper_trail...

No branch for Rails 2.3.x

Which tag should I install for Rails 2.3.8?

Using gem install paper_trail (I'm using RVM) installs Rails 3.x dependencies:

> gem install paper_trail
Successfully installed paper_trail-1.6.4
Successfully installed activesupport-3.0.3
Successfully installed activemodel-3.0.3
Successfully installed arel-2.0.7
Successfully installed rack-1.2.1
Successfully installed rack-test-0.5.7
Successfully installed rack-mount-0.6.13
Successfully installed erubis-2.6.6
8 gems installed

Option to apply migrations to previous versions?

It would be really nice if there was an option to apply migrations to previous versions. I've been using paper trail, and I ran into a problem after renaming a column - all my previous versions were returning nil for the updated attribute, I ended up having to go through all the versions and manually change the YAML to reflect the new attribute name.

This could probably be done in the migration by explicitly modifying the YAML dump, but this is an added layer of complexity that's easy to forget about, and requires going back and making sure that the changes won't mess up previous versions.

ActiveRecord::RecordNotSaved thrown, when calling clear on a new record

In a case where an association is build (not saved) and then cleared, rails calls destroy or delete.
An exception is thrown - "ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved".

I found adding this fixed it:
def record_destroy
return if new_record?
...
end
Maybe it could be added too record_update as well.

Here is a case.
class Blog < ActiveRecord::Base
has_paper_trail
has_many :posts
end
class Post < ActiveRecord::Base
has_paper_trail
belongs_to :blog
end

class BlogsController < ApplicationController
def action
@blog.posts.build
@blog.posts.clear #now i dont want it any more
end
end

Thanks for the great plugin, i learnt a lot by looking at the code.
Thanks
Ben

internationalization

HI,

Have you some hack to modify 'create', 'update' and 'destroy' terms ? How i can translate this in the base or in the view ?

thk for this nice plugin.

ID primary key on versions doesn't allow use of archive engine in MySQL

The auto increment ID column won't allow us to make use of an archive engine on the table (MySQL). We tried to remove the ID hoping it wasn't being used but I found out that it was in this seemingly redundant order by clause. I just wanted to suggest that you ditch the ID column and use only the created_at timestamp for the ordering so that archive engine setup would be possible.

ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'id' in 'order clause': SELECT * FROM versions WHERE (versions.item_id = 608 AND versions.item_type = 'Opportunity') ORDER BY created_at ASC, id ASC

Update not working

Hi,

Updating a record is not working for me.

Looking at the code that is called for the "before_update", I cannot figure out what does this do:
def changed_and_we_care?
changed? and !(changed - self.class.ignore).empty?
end

I cannot figure out where "changed" and "changed?" is coming from.

Update README

On instalation, where it reads
bundle exec rails generate paper_trail
it should be
bundle exec rails generate paper_trail:install

Ability to store reference specific version

I'm trying to use PaperTrail for addresses, so that users can update them, but past orders can still reference the old addresses. At present, I had thought to store the last version that is stored by PaperTrail, but I did not sufficiently understand it's implementation. PaperTrail stores the before state of the model for that version, such that reify calls what it was before the version.

I sought a workaround where I stored a reference to the last version, but used next_version on it to get the one I wanted. However, it is not working when the next version is the live version of the model instance. I could in fact, check if this is nil and then return the current model, but was thinking if there is a bug in next_version.

I guess this is more of a feature request to provide more official support for storing references to specific versions.

[Feature Request] Find specific attribute updates for a versioned model

Hello,

I have a customer model which have a column named status. I need to generate a report having all status changes on a specific customer and all customers.

Something like Customer.versions.changed(:status).

I'm trying to implement this manually with a pseudo model here but no success at moment.

Suggestions to do that with paper trail?

Best regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.