Use the "paper_trail" gem to track versions of records

Posted . Visible to the public.

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

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.

Arne Hartherz
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2012-08-01 08:17)