Toll free (US) : +1 (888) 838-3532 | NYC: +1 (646) 491-6866

Paper trail lets us track all the changes in the models data for the purpose of its editing and versioning. By using this gem, we can see how a model looks, at every stage of its life-cycle and we can take it back to any version of the model data and we can even undo all the changes after a record has been destroyed so as to restore it completely.

gem ‘paper_trail’ run bundle install to install it

After bundle install you can run the following command for adding versions table to your database

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

Add has_paper_trail method to your models for tracking.

class Product < ActiveRecord::Base
  	has_paper_trail
	end

If you are using a current_user method then you can track who is responsible for particular change by the below callback

class ApplicationController
	  before_action :set_paper_trail_whodunnit
	end


Features of paper trail gem

It stores each and every change happened in the model like create, update and destroy
It does not store any updates unless if any modifications
It allows you to get every version including the actual and even once destroyed

Basic Usage

Now you have a versions method which returns all the changes in particular model

product = Product.find 2
	product.versions
# [, , ...]

Based on the vesrion you can find the changes that happened in a model

v = product.versions.last

v.event # it returns update / create / destroy
v.whodunnit #it returns a user id who did this
v.reify the poduct as it was before the update

you can navigate versions by using previous_version and next_version methods

product = product.previous_version

product = product.next_version #it returns nil if there is no object

product.versions.last.whodunnit #it returns the user who did the particular change

RailsCarma has been providing ruby on rails development services from past 8 years Our developers are well versed with doing all kinds of Ruby on Rails web development work and handling any kind of project. Contact us to know more about our development skills and the projects which we can handle.

WhatsApp chat