Read more

Use the "paper_trail" gem to track versions of records

Arne Hartherz
August 01, 2012Software engineer at makandra GmbH

paper_trail is an excellent gem to track record versions and changes.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

You almost never want to reimplement something like it yourself. If you need to log some extra information, you can add them on top.

It comes with a really good README file that holds lots of examples. I'll show you only some of its features here:

  • Setting up a model to track changes
    : Just add has_paper_trail to it:
    class User < ActiveRecord::Base
    has_paper_trail
    end

  • Accessing a previous version
    : Saying user.previous_version gives you a User instance with the attributes from that previous version. You can also use something like user.version_at(10.hours.ago).

  • Diffing attribute changes
    : Access a Version directly, like user.versions.last and call its changeset:
    user.versions.last.changeset
    => { 'first_name' => [ 'Alice', 'Bob' ], 'gender' => [ 'female', 'male' ] }

  • Tracking who made the changes
    : It uses current_user from your controllers, if present. Awesome!

Check out the documentation for more features.

Posted by Arne Hartherz to makandra dev (2012-08-01 10:17)