I was working with paper_trail today. It is an excellent gem that saves a history of your creates, updates, and destroys for Rails ActiveRecord models. I am adding this gem to an existing project that already has records in the database. I need to put these records in the paper_trail’s
versions table, so I can use a query that checks to see how many versions exist for a particular model instance. Just to make it clean, so I don’t have to query both the model and the versions table, I want to add that initial “create” version for all of my existing records. After reading through the source, I could not figure out an easy way to do it with the existing codebase, so I decided to create a simple monkey patch and rake task that will version all of my existing records.
This rake task adds a new instance method, so the model can have access to the private method “record_create” in paper_trail. Then it takes all model classes, iterates through them and detects the classes that have paper_trail enabled. If the record has no versions, then it creates the initial version and prints out the result. Now I have a fresh set of data that makes it look like paper_trail was installed to begin with (minus any history I’ve already lost).