SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Paper Trail Gem:
Track Changes to Your
Models Data
Howdy, today I am going to talk about the
versioning. How to specifically version your models?
So wondering what I am talking about? What is
that versioning and my models?
Let me explain you with an example.
If you have created a specific document that many
people can edit; yes, just similar to Google Docs.
Let’s say, it’s a client proposal and you want your
colleagues to do have a look and if required then
make the validate changes. After sharing the
document with your colleagues, in case someone
does @#$%***&% to your doc or if someone has
updated your doc with the required changes, then
you will not be able to see all the previous versions
of the doc and who changed it. This is the most
common scenario as it creates a big mess.
How To Track changes to your models’ data
To help you out and track all the changes as well as
who has done this, we’re going to use Paper Trail
gem. It is a simplified version of Google Docs. A
very, very simplified. This gem lets you track all the
changes, as the purpose of editing and versioning.
And making use of it, you can be able to see all the
previous versions of the file and if required you
can rollback to a previous version of your choice.
You can even undo all the changes after a record
has been destroyed so as to restore it completely.
Why Paper trail?
It’s a one stop solution for text data:
It helps to focus on what to look for. Helps to
focus on auditing or versioning.
Relevant data is split across directories, multiple
apps and systems. So instead of source, they can
be managed by username, IP address, message ID.
Setup The App
I am not going to build the application from
scratch. Instead have pulled the code from Github.
Git clone : https://github.com/
Run the migration, bundle and start the app
rake db:migrate
bundle install
rails server
If you head over to localhost:3000, you should see
the following :
PaperTrail
PaperTrail to automatically keep track of what
happened to our documents.
# Gemfile
gem 'paper_trail'
Now, 3 steps in one line to get it to work :
bundle install && bundle exec rails generate
paper_trail:install && bundle exec rake db:migrate
Restart your server before continuing.
After that, add PaperTrail to the model we
want to version :
# app/models/document.rb
class Document < ActiveRecord::Base
belongs_to :user
has_paper_trail
def user_name
user ? user.name : '‘
end
end
And that’s it ! Everytime we save our model, we’ll
get the previous version saved by PaperTrail :
PaperTrail::Version.all
# => #<ActiveRecord::Relation
[#<PaperTrail::Version id: 1, item_type: "Document",
item_id: 1, event: "update", whodunnit: "1", object:
"---nid: 1nname: Abczncontent: aaanuser_id:
1ncreat...", created_at: "2014-09-26 15:38:14">]>
Listing the previous versions
# app/helpers/documents_helper.rb
module DocumentsHelper
def
find_version_author_name(version)
user =
User.find_version_author(version)
user ? user.name : ''
end
end
# app/models/user.rb
class User < ActiveRecord::Base
has_many :documents
def
self.find_version_author(version)
find(version.terminator)
end
end
Now, let’s add the actual list of versions to
the edit document view as a partial :
Ruby:
And render this partial after the Document
form :
# app/views/documents/edit.html.erb
...
<%= render 'form' %>
<%= render 'documents/versions‘
,document: @document %>
Now you can udpate any document a few times. You
should see the list of versions growing!
Add Diff & Rollback
First, we’re going to update the edit document
view to add action to the links :
Then we need the routes :
# config/routes.rb
resources :documents do
resources :versions, only: [:destroy] do
member do
get :diff, to: 'versions#diff‘
patch :rollback, to: 'versions#rollback‘
end
end
end
You can also rollback to a previous version! Pretty
cool, huh! So for that we’re going to use the very
nice gem Diffy. Diffy gives us an easy way to diff
content (files or strings) in Ruby by using Unix
diff.
And finally, we create the controller :
Diff with Diffy
Add the gem to your Gemfile :
# Gemfile
...
gem 'paper_trail‘
gem 'diffy‘
...
bundle install and restart your server.
Now the actual diff view is pretty simple to
build. We’re going to create it in app/ views/
versions/ :
If you try it, you should see something like
that:.
Very nice! Now, our app is missing one very
important feature. Its a way to bring back
documents from the graveyard!
Custom Version Class
Adding a custom version class is actually quite
easy.
First, we need to generate a migration :
rails g migration create_document_versions
You can paste this in it :
The corresponding model:
Note the default_scope I added.
Bring back Documents
The actions in our controllers:
And a view to list the deleted documents :
# app/views/documents/deleted.html.erb
Bring back documents
Now try it! Delete a document and it will appear
in the list of deleted
MetaData
Remember when we created the migration for you
custom Document Version model ? We’re going to
use those!
# app/models/document.rb
...
has_paper_trail class_name: 'DocumentVersion',
meta: { author_username: :user_name,
word_count: :count_word }
When PaperTrail generate a new version, it will
call the defined methods (user_name) on
document an save it in the specified field
(author_username).
We need to add a method named count_word.
def count_word
content.split(' ').count
end
def count_word
content.split(' ').count
end
And since we added all those information, we
should show it in our list of versions.
And save a few versions to see the metadata!
Who needs 100 versions ?
The last trick, We probably don’t need the 100
previous versions, 10 to 30 should be enough. You
can define that in PaperTrail configuration :
# config/initializers/paper_trail.rb
PaperTrail.config.version_limit = 10
Source code -
https://github.com/airblade/paper_trail#1c-basic-
usage
Features:
1.Stores every update and destroy.
2.Only store updates that has been changed.
3.You can have all the version, including the
original, if it even destroyed once.
4.You can get every version even if the schema
has since changed.
5.Automatically record a responsible controller
current user method.
6.Allows you to set who is responsible at model-
level (useful for migrations).
7.No configuration necessary.
8.Can be turned off/on.
9.Everything can be stored in a single database
table.
10.Thoroughly tested.
Interested in installation
Bacancy Technology has been providing ruby on
rails development services from past 5 years. We
own a strong ROR workforce and have
successfully completed 200+ Rails Application.
Our developers have in-depth knowledge and
skilful expertise in doing all kinds of Ruby on
Rails development work and dealing with any kind
of project.
Numbers of big organizations have made their
way to the top using Rails, and possibly you can
be the next, with the help of Ruby on Rails.
Paper trail gem

Contenu connexe

Similaire à Paper trail gem

Introduction to Docker and Containers- Learning Simple
Introduction to Docker and Containers- Learning SimpleIntroduction to Docker and Containers- Learning Simple
Introduction to Docker and Containers- Learning SimpleSandeep Hijam
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfJohnLeo57
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Umair Amjad
 
Mulesoft - Documentation (Automation)
Mulesoft - Documentation (Automation)Mulesoft - Documentation (Automation)
Mulesoft - Documentation (Automation)Vamsi Krishna
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...Paul Jensen
 
Build a video chat application with twilio, rails, and javascript (part 1)
Build a video chat application with twilio, rails, and javascript (part 1)Build a video chat application with twilio, rails, and javascript (part 1)
Build a video chat application with twilio, rails, and javascript (part 1)Katy Slemon
 
Rails Rookies Bootcamp - Blogger
Rails Rookies Bootcamp - BloggerRails Rookies Bootcamp - Blogger
Rails Rookies Bootcamp - BloggerNathanial McConnell
 
Basic iOS Training with SWIFT - Part 4
Basic iOS Training with SWIFT - Part 4Basic iOS Training with SWIFT - Part 4
Basic iOS Training with SWIFT - Part 4Manoj Ellappan
 
StatsD DevOps Boulder 7/20/15
StatsD DevOps Boulder 7/20/15StatsD DevOps Boulder 7/20/15
StatsD DevOps Boulder 7/20/15Mark Morris
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdfBOSC Tech Labs
 
Automatic documantation with mule
Automatic documantation with mule Automatic documantation with mule
Automatic documantation with mule AbdulImrankhan7
 
Automatic documentation with mule
Automatic documentation with muleAutomatic documentation with mule
Automatic documentation with muleF K
 
Automatic documentation with mule
Automatic documentation with mule Automatic documentation with mule
Automatic documentation with mule javeed_mhd
 
Automatic documantation with mule
Automatic documantation with mule Automatic documantation with mule
Automatic documantation with mule mdfkhan625
 
Automatic documentation with mule
Automatic documentation with muleAutomatic documentation with mule
Automatic documentation with muleMohammed246
 

Similaire à Paper trail gem (20)

Introduction to Docker and Containers- Learning Simple
Introduction to Docker and Containers- Learning SimpleIntroduction to Docker and Containers- Learning Simple
Introduction to Docker and Containers- Learning Simple
 
What is Swagger?
What is Swagger?What is Swagger?
What is Swagger?
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdf
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3
 
Mulesoft - Documentation (Automation)
Mulesoft - Documentation (Automation)Mulesoft - Documentation (Automation)
Mulesoft - Documentation (Automation)
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
 
Django by rj
Django by rjDjango by rj
Django by rj
 
Build a video chat application with twilio, rails, and javascript (part 1)
Build a video chat application with twilio, rails, and javascript (part 1)Build a video chat application with twilio, rails, and javascript (part 1)
Build a video chat application with twilio, rails, and javascript (part 1)
 
Rails Rookies Bootcamp - Blogger
Rails Rookies Bootcamp - BloggerRails Rookies Bootcamp - Blogger
Rails Rookies Bootcamp - Blogger
 
Basic iOS Training with SWIFT - Part 4
Basic iOS Training with SWIFT - Part 4Basic iOS Training with SWIFT - Part 4
Basic iOS Training with SWIFT - Part 4
 
XCode8.0
XCode8.0XCode8.0
XCode8.0
 
Assignment 2
Assignment 2Assignment 2
Assignment 2
 
StatsD DevOps Boulder 7/20/15
StatsD DevOps Boulder 7/20/15StatsD DevOps Boulder 7/20/15
StatsD DevOps Boulder 7/20/15
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
 
Automatic documantation with mule
Automatic documantation with mule Automatic documantation with mule
Automatic documantation with mule
 
Automatic documentation with mule
Automatic documentation with muleAutomatic documentation with mule
Automatic documentation with mule
 
Automatic documentation with mule
Automatic documentation with mule Automatic documentation with mule
Automatic documentation with mule
 
Automatic documantation with mule
Automatic documantation with mule Automatic documantation with mule
Automatic documantation with mule
 
Documantation with mule
Documantation with mule Documantation with mule
Documantation with mule
 
Automatic documentation with mule
Automatic documentation with muleAutomatic documentation with mule
Automatic documentation with mule
 

Dernier

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 

Dernier (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Paper trail gem

  • 1. Paper Trail Gem: Track Changes to Your Models Data
  • 2. Howdy, today I am going to talk about the versioning. How to specifically version your models? So wondering what I am talking about? What is that versioning and my models? Let me explain you with an example. If you have created a specific document that many people can edit; yes, just similar to Google Docs. Let’s say, it’s a client proposal and you want your colleagues to do have a look and if required then make the validate changes. After sharing the document with your colleagues, in case someone does @#$%***&% to your doc or if someone has updated your doc with the required changes, then you will not be able to see all the previous versions of the doc and who changed it. This is the most common scenario as it creates a big mess. How To Track changes to your models’ data To help you out and track all the changes as well as who has done this, we’re going to use Paper Trail gem. It is a simplified version of Google Docs. A very, very simplified. This gem lets you track all the changes, as the purpose of editing and versioning.
  • 3. And making use of it, you can be able to see all the previous versions of the file and if required you can rollback to a previous version of your choice. You can even undo all the changes after a record has been destroyed so as to restore it completely. Why Paper trail? It’s a one stop solution for text data: It helps to focus on what to look for. Helps to focus on auditing or versioning. Relevant data is split across directories, multiple apps and systems. So instead of source, they can be managed by username, IP address, message ID. Setup The App I am not going to build the application from scratch. Instead have pulled the code from Github. Git clone : https://github.com/
  • 4. Run the migration, bundle and start the app rake db:migrate bundle install rails server If you head over to localhost:3000, you should see the following : PaperTrail PaperTrail to automatically keep track of what happened to our documents. # Gemfile gem 'paper_trail' Now, 3 steps in one line to get it to work : bundle install && bundle exec rails generate paper_trail:install && bundle exec rake db:migrate Restart your server before continuing.
  • 5. After that, add PaperTrail to the model we want to version : # app/models/document.rb class Document < ActiveRecord::Base belongs_to :user has_paper_trail def user_name user ? user.name : '‘ end end And that’s it ! Everytime we save our model, we’ll get the previous version saved by PaperTrail : PaperTrail::Version.all # => #<ActiveRecord::Relation [#<PaperTrail::Version id: 1, item_type: "Document", item_id: 1, event: "update", whodunnit: "1", object: "---nid: 1nname: Abczncontent: aaanuser_id: 1ncreat...", created_at: "2014-09-26 15:38:14">]>
  • 6. Listing the previous versions # app/helpers/documents_helper.rb module DocumentsHelper def find_version_author_name(version) user = User.find_version_author(version) user ? user.name : '' end end # app/models/user.rb class User < ActiveRecord::Base has_many :documents def self.find_version_author(version) find(version.terminator) end end Now, let’s add the actual list of versions to the edit document view as a partial : Ruby:
  • 7.
  • 8. And render this partial after the Document form : # app/views/documents/edit.html.erb ... <%= render 'form' %> <%= render 'documents/versions‘ ,document: @document %> Now you can udpate any document a few times. You should see the list of versions growing!
  • 9. Add Diff & Rollback First, we’re going to update the edit document view to add action to the links : Then we need the routes : # config/routes.rb resources :documents do resources :versions, only: [:destroy] do member do get :diff, to: 'versions#diff‘ patch :rollback, to: 'versions#rollback‘ end end end
  • 10. You can also rollback to a previous version! Pretty cool, huh! So for that we’re going to use the very nice gem Diffy. Diffy gives us an easy way to diff content (files or strings) in Ruby by using Unix diff. And finally, we create the controller :
  • 11. Diff with Diffy Add the gem to your Gemfile : # Gemfile ... gem 'paper_trail‘ gem 'diffy‘ ... bundle install and restart your server. Now the actual diff view is pretty simple to build. We’re going to create it in app/ views/ versions/ :
  • 12. If you try it, you should see something like that:.
  • 13. Very nice! Now, our app is missing one very important feature. Its a way to bring back documents from the graveyard! Custom Version Class Adding a custom version class is actually quite easy. First, we need to generate a migration : rails g migration create_document_versions You can paste this in it :
  • 14. The corresponding model: Note the default_scope I added. Bring back Documents
  • 15. The actions in our controllers:
  • 16.
  • 17. And a view to list the deleted documents : # app/views/documents/deleted.html.erb Bring back documents
  • 18. Now try it! Delete a document and it will appear in the list of deleted MetaData Remember when we created the migration for you custom Document Version model ? We’re going to use those! # app/models/document.rb ... has_paper_trail class_name: 'DocumentVersion', meta: { author_username: :user_name, word_count: :count_word } When PaperTrail generate a new version, it will call the defined methods (user_name) on document an save it in the specified field (author_username). We need to add a method named count_word. def count_word content.split(' ').count end def count_word content.split(' ').count end
  • 19. And since we added all those information, we should show it in our list of versions. And save a few versions to see the metadata!
  • 20. Who needs 100 versions ? The last trick, We probably don’t need the 100 previous versions, 10 to 30 should be enough. You can define that in PaperTrail configuration : # config/initializers/paper_trail.rb PaperTrail.config.version_limit = 10 Source code - https://github.com/airblade/paper_trail#1c-basic- usage Features: 1.Stores every update and destroy. 2.Only store updates that has been changed. 3.You can have all the version, including the original, if it even destroyed once. 4.You can get every version even if the schema has since changed. 5.Automatically record a responsible controller current user method. 6.Allows you to set who is responsible at model- level (useful for migrations). 7.No configuration necessary. 8.Can be turned off/on. 9.Everything can be stored in a single database table. 10.Thoroughly tested.
  • 21. Interested in installation Bacancy Technology has been providing ruby on rails development services from past 5 years. We own a strong ROR workforce and have successfully completed 200+ Rails Application. Our developers have in-depth knowledge and skilful expertise in doing all kinds of Ruby on Rails development work and dealing with any kind of project. Numbers of big organizations have made their way to the top using Rails, and possibly you can be the next, with the help of Ruby on Rails.