Many of us have already heard about PaperTrail gem and its use for versioning of model. I found it very useful for purpose of debugging. Lets have a quick look at exactly what is PapertTrail gem and how we can use it for purpose of debugging.

PaperTrail and Versions:

  • When we add papertrail gem in our rails app and run migration for same at that time it creates Version table for us in our DB.
  • When we use it in particular model and perform any kind create, update operation on it then each time it creates associated versions record for model.
  • Each version record contains information about all attributes changes, its previous values and current values.

3 Simple steps to add it in rails application and its ready to use:

  • Add PaperTrail to your Gemfile.

    gem 'paper_trail'

1.Add a versions table to your database and an initializer file for configuration

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

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

class Package < ActiveRecord::Base

Once we are set with above steps and want to check its working or not then we can just update any one record and call .versions on object.

e.g Package.find(1).versions

It will return all associated versions records which contains really useful information event, whodunnit, object_changes etc.

event : Which event was called on object like create or update.

whodunnit : Which user did it.

object_changes: It contains log of previous and current values of attributes.

item: It contains object information.

Now I am going to explain about how it can we helpful if we are using rails api for multiple applications with different functionality and same model.

Consider following image and its each step has different application and consider somehow it deals with single model.

enter image description here

In such environment if any bad data created for package model due to some bug in any of this app then it becomes really difficult to debug which app contains bug.

How versions can help us here ?

  1. We can check all associated version records of package.
  2. Version records in sequence give us whole picture about what exactly
  3. By looking at version record and its object changes we
    can guess from where it can happen.
  4. It contains user info at each
    step so that can also help us.(For single application it is easy to
    track who did it but in case of many applications using same api and
    same object then in this case we need user info at each version

That's all about it. Hope this will help. Thanks!