Search code examples
ruby-on-railsrubyrubygemsruby-on-rails-5paper-trail-gem

restore main Object to a Specific Version by using Paper Trail


How I can apply changes present in specific version to the main Object?

For Example:

Let's say there is a Project model. Whenever a Project Record gets updated, system creates a version. Now I've a requirement where user can move this project record to any specific version and ONLY update all attributes which were changed during that Version.

 Project 1 has following Versions:
  V5 
  V4
  V3
  V2
  V1

 if user wants he can move Project to any of these 5 Versions and apply the changes 
 made in that version in project record.

I'm using

ruby 2.5.3, Rails 5.1.6.2 & paper_trail (10.3.0)


Solution

  • The docs says that each version also has an created_at attribute. So you can find the version at a given time:

    widget = widget.paper_trail.version_at(1.day.ago)  # the widget as it was one day ago
    widget.save                                        # reverted
    

    If you know what version the user wants, you also know the created_at so that way you can set it to the correct version.

    wanted_version = # Find the correct version that the user wants
    widget = widget.paper_trail.version_at(wanted_version.created_at)
    widget.save