[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-7680":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":17,"stars30d":18,"stars90d":16,"forks30d":16,"starsTrendScore":19,"compositeScore":20,"rankGlobal":10,"rankLanguage":10,"license":21,"archived":22,"fork":22,"defaultBranch":23,"hasWiki":24,"hasPages":22,"topics":25,"createdAt":10,"pushedAt":10,"updatedAt":31,"readmeContent":32,"aiSummary":33,"trendingCount":16,"starSnapshotCount":16,"syncStatus":34,"lastSyncTime":35,"discoverSource":36},7680,"paper_trail","paper-trail-gem\u002Fpaper_trail","paper-trail-gem","Track changes to your rails models","",null,"Ruby",7022,910,60,6,0,3,24,1,68.78,"MIT License",false,"master",true,[26,27,28,29,30],"activerecord","audit","log","rails","ruby","2026-06-12 04:00:35","# PaperTrail\n\n[![Build Status][4]][5]\n[![Gem Version][53]][54]\n[![SemVer][55]][56]\n\nTrack changes to your models, for auditing or versioning. See how a model looked\nat any stage in its lifecycle, revert it to any version, or restore it after it\nhas been destroyed.\n\n## Documentation\n\nThis is the _user guide_. See also, the\n[API reference](https:\u002F\u002Fwww.rubydoc.info\u002Fgems\u002Fpaper_trail).\n\nChoose version:\n[Unreleased](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fmaster\u002FREADME.md),\n[17.0](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv17.0.0\u002FREADME.md),\n[16.0](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv16.0.0\u002FREADME.md),\n[15.2](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv15.2.0\u002FREADME.md),\n[14.0](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv14.0.0\u002FREADME.md),\n[13.0](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv13.0.0\u002FREADME.md),\n[12.3](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv12.3.0\u002FREADME.md),\n[11.1](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv11.1.0\u002FREADME.md),\n[10.3](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv10.3.1\u002FREADME.md),\n[9.2](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv9.2.0\u002FREADME.md),\n[8.1](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv8.1.2\u002FREADME.md),\n[7.1](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv7.1.3\u002FREADME.md),\n[6.0](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv6.0.2\u002FREADME.md),\n[5.2](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv5.2.3\u002FREADME.md),\n[4.2](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv4.2.0\u002FREADME.md),\n[3.0](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv3.0.9\u002FREADME.md),\n[2.7](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv2.7.2\u002FREADME.md),\n[1.6](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fv1.6.5\u002FREADME.md)\n\n## Table of Contents\n\n\u003C!-- toc -->\n\n- [1. Introduction](#1-introduction)\n  - [1.a. Compatibility](#1a-compatibility)\n  - [1.b. Installation](#1b-installation)\n  - [1.c. Basic Usage](#1c-basic-usage)\n  - [1.d. API Summary](#1d-api-summary)\n  - [1.e. Configuration](#1e-configuration)\n- [2. Limiting What is Versioned, and When](#2-limiting-what-is-versioned-and-when)\n  - [2.a. Choosing Lifecycle Events To Monitor](#2a-choosing-lifecycle-events-to-monitor)\n  - [2.b. Choosing When To Save New Versions](#2b-choosing-when-to-save-new-versions)\n  - [2.c. Choosing Attributes To Monitor](#2c-choosing-attributes-to-monitor)\n  - [2.d. Turning PaperTrail Off](#2d-turning-papertrail-off)\n  - [2.e. Limiting the Number of Versions Created](#2e-limiting-the-number-of-versions-created)\n- [3. Working With Versions](#3-working-with-versions)\n  - [3.a. Reverting And Undeleting A Model](#3a-reverting-and-undeleting-a-model)\n  - [3.b. Navigating Versions](#3b-navigating-versions)\n  - [3.c. Diffing Versions](#3c-diffing-versions)\n  - [3.d. Deleting Old Versions](#3d-deleting-old-versions)\n  - [3.e. Queries](#3e-queries)\n  - [3.f. Defunct `item_id`s](#3f-defunct-item_ids)\n- [4. Saving More Information About Versions](#4-saving-more-information-about-versions)\n  - [4.a. Finding Out Who Was Responsible For A Change](#4a-finding-out-who-was-responsible-for-a-change)\n  - [4.b. Associations](#4b-associations)\n  - [4.c. Storing Metadata](#4c-storing-metadata)\n- [5. ActiveRecord](#5-activerecord)\n  - [5.a. Single Table Inheritance (STI)](#5a-single-table-inheritance-sti)\n  - [5.b. Configuring the `versions` Association](#5b-configuring-the-versions-association)\n  - [5.c. Generators](#5c-generators)\n  - [5.d. Protected Attributes](#5d-protected-attributes)\n- [6. Extensibility](#6-extensibility)\n  - [6.a. Custom Version Classes](#6a-custom-version-classes)\n  - [6.b. Custom Serializer](#6b-custom-serializer)\n  - [6.c. Custom Object Changes](#6c-custom-object-changes)\n  - [6.d. Excluding the Object Column](#6d-excluding-the-object-column)\n  - [6.e. Error handling](#6e-error-handling)\n- [7. Testing](#7-testing)\n  - [7.a. Minitest](#7a-minitest)\n  - [7.b. RSpec](#7b-rspec)\n  - [7.c. Cucumber](#7c-cucumber)\n  - [7.d. Spork](#7d-spork)\n  - [7.e. Zeus or Spring](#7e-zeus-or-spring)\n- [8. PaperTrail Plugins](#8-papertrail-plugins)\n- [9. Integration with Other Libraries](#9-integration-with-other-libraries)\n- [10. Related Libraries and Ports](#10-related-libraries-and-ports)\n- [Articles](#articles)\n- [Problems](#problems)\n- [Contributors](#contributors)\n- [Contributing](#contributing)\n- [Inspirations](#inspirations)\n- [Intellectual Property](#intellectual-property)\n\n\u003C!-- tocstop -->\n\n## 1. Introduction\n\n### 1.a. Compatibility\n\n| paper_trail | ruby     | activerecord  |\n|-------------|----------|---------------|\n| unreleased  | >= 3.2.0 | >= 7.1, \u003C= 8.1 |\n| 16          | >= 3.0.0 | >= 6.1, \u003C= 8.0 |\n| 15.2        | >= 3.0.0 | >= 6.1, \u003C= 7.2 |\n| 15.1        | >= 3.0.0 | >= 6.1, \u003C= 7.1 |\n| 15          | >= 3.0.0 | >= 6.1, \u003C= 7.1 |\n| 14          | >= 2.7.0 | >= 6.0, \u003C 7.1 |\n| 13          | >= 2.6.0 | >= 5.2, \u003C 7.1 |\n| 12          | >= 2.6.0 | >= 5.2, \u003C 7.1 |\n| 11          | >= 2.4.0 | >= 5.2, \u003C 6.1 |\n| 10          | >= 2.3.0 | >= 4.2, \u003C 6.1 |\n| 9           | >= 2.3.0 | >= 4.2, \u003C 5.3 |\n| 8           | >= 2.2.0 | >= 4.2, \u003C 5.2 |\n| 7           | >= 2.1.0 | >= 4.0, \u003C 5.2 |\n| 6           | >= 1.9.3 | >= 4.0, \u003C 5.2 |\n| 5           | >= 1.9.3 | >= 3.0, \u003C 5.1 |\n| 4           | >= 1.8.7 | >= 3.0, \u003C 5.1 |\n| 3           | >= 1.8.7 | >= 3.0, \u003C 5   |\n| 2           | >= 1.8.7 | >= 3.0, \u003C 4   |\n| 1           | >= 1.8.7 | >= 2.3, \u003C 3   |\n\nExperts: to install incompatible versions of activerecord, see\n`paper_trail\u002Fcompatibility.rb`.\n\n### 1.b. Installation\n\n1. Add PaperTrail to your `Gemfile` and run [`bundle`][57].\n\n    `gem 'paper_trail'`\n\n1. Add a `versions` table to your database:\n\n    ```\n    bundle exec rails generate paper_trail:install [--with-changes] [--uuid]\n    bundle exec rails db:migrate\n    ```\n\n    See [section 5.c. Generators](#5c-generators) for details.\n\n1. Add `has_paper_trail` to the models you want to track.\n\n    ```ruby\n    class Widget \u003C ActiveRecord::Base\n      has_paper_trail\n    end\n    ```\n\n1. If your controllers have a `current_user` method, you can easily [track who\nis responsible for changes](#4a-finding-out-who-was-responsible-for-a-change)\nby adding a controller callback.\n\n    ```ruby\n    class ApplicationController\n      before_action :set_paper_trail_whodunnit\n    end\n    ```\n\n### 1.c. Basic Usage\n\nYour models now have a `versions` method which returns the \"paper trail\" of\nchanges to your model.\n\n```ruby\nwidget = Widget.find 42\nwidget.versions\n# [\u003CPaperTrail::Version>, \u003CPaperTrail::Version>, ...]\n```\n\nOnce you have a version, you can find out what happened:\n\n```ruby\nv = widget.versions.last\nv.event # 'update', 'create', 'destroy'. See also: \"The versions.event Column\"\nv.created_at\nv.whodunnit # ID of `current_user`. Requires `set_paper_trail_whodunnit` callback.\nwidget = v.reify # The widget as it was before the update (nil for a create event)\n```\n\nPaperTrail stores the pre-change version of the model, unlike some other\nauditing\u002Fversioning plugins, so you can retrieve the original version.  This is\nuseful when you start keeping a paper trail for models that already have records\nin the database.\n\n```ruby\nwidget = Widget.find 153\nwidget.name                                 # 'Doobly'\n\n# Add has_paper_trail to Widget model.\n\nwidget.versions                             # []\nwidget.update name: 'Wotsit'\nwidget.versions.last.reify.name             # 'Doobly'\nwidget.versions.last.event                  # 'update'\n```\n\nThis also means that PaperTrail does not waste space storing a version of the\nobject as it currently stands.  The `versions` method gives you previous\nversions; to get the current one just call a finder on your `Widget` model as\nusual.\n\nHere's a helpful table showing what PaperTrail stores:\n\n| *Event*        | *create* | *update* | *destroy* |\n| -------------- | -------- | -------- | --------- |\n| *Model Before* | nil      | widget   | widget    |\n| *Model After*  | widget   | widget   | nil       |\n\nPaperTrail stores the values in the Model Before row.  Most other\nauditing\u002Fversioning plugins store the After row.\n\n### 1.d. API Summary\n\nAn introductory sample of common features.\n\nWhen you declare `has_paper_trail` in your model, you get these methods:\n\n```ruby\nclass Widget \u003C ActiveRecord::Base\n  has_paper_trail\nend\n\n# Returns this widget's versions.  You can customise the name of the\n# association, but overriding this method is not supported.\nwidget.versions\n\n# Return the version this widget was reified from, or nil if it is live.\n# You can customise the name of the method.\nwidget.version\n\n# Returns true if this widget is the current, live one; or false if it is from\n# a previous version.\nwidget.paper_trail.live?\n\n# Returns who put the widget into its current state.\nwidget.paper_trail.originator\n\n# Returns the widget (not a version) as it looked at the given timestamp.\nwidget.paper_trail.version_at(timestamp)\n\n# Returns the widget (not a version) as it was most recently.\nwidget.paper_trail.previous_version\n\n# Returns the widget (not a version) as it became next.\nwidget.paper_trail.next_version\n```\n\nAnd a `PaperTrail::Version` instance (which is just an ordinary ActiveRecord\ninstance, with all the usual methods) has methods such as:\n\n```ruby\n# Returns the item restored from this version.\nversion.reify(options = {})\n\n# Return a new item from this version\nversion.reify(dup: true)\n\n# Returns who put the item into the state stored in this version.\nversion.paper_trail_originator\n\n# Returns who changed the item from the state it had in this version.\nversion.terminator\nversion.whodunnit\nversion.version_author\n\n# Returns the next version.\nversion.next\n\n# Returns the previous version.\nversion.previous\n\n# Returns the index of this version in all the versions.\nversion.index\n\n# Returns the event that caused this version (create|update|destroy).\nversion.event\n```\n\nThis is just a sample of common features. Keep reading for more.\n\n### 1.e. Configuration\n\nMany aspects of PaperTrail are configurable for individual models; typically\nthis is achieved by passing options to the `has_paper_trail` method within\na given model.\n\nSome aspects of PaperTrail are configured globally for all models. These\nsettings are assigned directly on the `PaperTrail.config` object.\nA common place to put these settings is in a Rails initializer file\nsuch as `config\u002Finitializers\u002Fpaper_trail.rb` or in an environment-specific\nconfiguration file such as `config\u002Fenvironments\u002Ftest.rb`.\n\n#### 1.e.1 Global\n\nGlobal configuration options affect all threads.\n\n- association_reify_error_behaviour\n- enabled\n- has_paper_trail_defaults\n- object_changes_adapter\n- serializer\n- version_limit\n- version_error_behavior\n\nSyntax example: (options described in detail later)\n\n```ruby\n# config\u002Finitializers\u002Fpaper_trail.rb\nPaperTrail.config.enabled = true\nPaperTrail.config.has_paper_trail_defaults = {\n  on: %i[create update destroy]\n}\nPaperTrail.config.version_limit = 3\n````\n\nThese options are intended to be set only once, during app initialization (eg.\nin `config\u002Finitializers`). It is unsafe to change them while the app is running.\nIn contrast, `PaperTrail.request` has various options that only apply to a\nsingle HTTP request and thus are safe to use while the app is running.\n\n## 2. Limiting What is Versioned, and When\n\n### 2.a. Choosing Lifecycle Events To Monitor\n\nYou can choose which events to track with the `on` option.  For example, if\nyou only want to track `update` events:\n\n```ruby\nclass Article \u003C ActiveRecord::Base\n  has_paper_trail on: [:update]\nend\n```\n\n`has_paper_trail` installs [callbacks][52] for the specified lifecycle events.\n\nThere are four potential callbacks, and the default is to install all four, ie.\n`on: [:create, :destroy, :touch, :update]`.\n\n#### The `versions.event` Column\n\nYour `versions` table has an `event` column with three possible values:\n\n| *event* | *callback*    |\n| ------- | ------------- |\n| create  | create        |\n| destroy | destroy       |\n| update  | touch, update |\n\nYou may also have the `PaperTrail::Version` model save a custom string in its\n`event` field instead of the typical `create`, `update`, `destroy`. PaperTrail\nadds an `attr_accessor` to your model named `paper_trail_event`, and will insert\nit, if present, in the `event` column.\n\n```ruby\na = Article.create\na.versions.size                           # 1\na.versions.last.event                     # 'create'\na.paper_trail_event = 'update title'\na.update title: 'My Title'\na.versions.size                           # 2\na.versions.last.event                     # 'update title'\na.paper_trail_event = nil\na.update title: 'Alternate'\na.versions.size                           # 3\na.versions.last.event                     # 'update'\n```\n\n#### Controlling the Order of AR Callbacks\n\nIf there are other callbacks in your model, their order relative to those\ninstalled by `has_paper_trail` may matter. If you need to control\ntheir order, use the `paper_trail_on_*` methods.\n\n```ruby\nclass Article \u003C ActiveRecord::Base\n  # Include PaperTrail, but do not install any callbacks. Passing the\n  # empty array to `:on` omits callbacks.\n  has_paper_trail on: []\n\n  # Add callbacks in the order you need.\n  paper_trail.on_destroy    # add destroy callback\n  paper_trail.on_update     # etc.\n  paper_trail.on_create\n  paper_trail.on_touch\nend\n```\n\nThe `paper_trail.on_destroy` method can be further configured to happen\n`:before` or `:after` the destroy event. Until PaperTrail 4, the default was\n`:after`. Starting with PaperTrail 5, the default is `:before`, to support\nActiveRecord 5. (see https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fpull\u002F683)\n\n### 2.b. Choosing When To Save New Versions\n\nYou can choose the conditions when to add new versions with the `if` and\n`unless` options. For example, to save versions only for US non-draft\ntranslations:\n\n```ruby\nclass Translation \u003C ActiveRecord::Base\n  has_paper_trail if:     Proc.new { |t| t.language_code == 'US' },\n                  unless: Proc.new { |t| t.type == 'DRAFT'       }\nend\n```\n\n#### Choosing Based on Changed Attributes\n\nStarting with PaperTrail 4.0, versions are saved during an after-callback. If\nyou decide whether to save a new version based on changed attributes,\nuse attribute_name_was instead of attribute_name.\n\n#### Saving a New Version Manually\n\nYou may want to save a new version regardless of options like `:on`, `:if`, or\n`:unless`. Or, in rare situations, you may want to save a new version even if\nthe record has not changed.\n\n```ruby\nmy_model.paper_trail.save_with_version\n```\n\n### 2.c. Choosing Attributes To Monitor\n\n#### Ignore\n\nIf you don't want a version created when only a certain attribute changes, you can `ignore` that attribute:\n\n```ruby\nclass Article \u003C ActiveRecord::Base\n  has_paper_trail ignore: [:title, :rating]\nend\n```\n\nChanges to just the `title` or `rating` will not create a version record.\nChanges to other attributes will create a version record.\n\n```ruby\na = Article.create\na.versions.length                         # 1\na.update title: 'My Title', rating: 3\na.versions.length                         # 1\na.update title: 'Greeting', content: 'Hello'\na.versions.length                         # 2\na.paper_trail.previous_version.title      # 'My Title'\n```\n\nNote: ignored fields will be stored in the version records. If you want to keep a field out of the versions table, use [`:skip`](#skip) instead of `:ignore`; skipped fields are also implicitly ignored.\n\nThe `:ignore` option can also accept `Hash` arguments that we are considering deprecating.\n\n```ruby\nclass Article \u003C ActiveRecord::Base\n  has_paper_trail ignore: [:title, { color: proc { |obj| obj.color == \"Yellow\" } }]\nend\n```\n\n#### Only\n\nOr, you can specify a list of the `only` attributes you care about:\n\n```ruby\nclass Article \u003C ActiveRecord::Base\n  has_paper_trail only: [:title]\nend\n```\n\nOnly changes to the `title` will create a version record.\n\n```ruby\na = Article.create\na.versions.length                         # 1\na.update title: 'My Title'\na.versions.length                         # 2\na.update content: 'Hello'\na.versions.length                         # 2\na.paper_trail.previous_version.content    # nil\n```\n\nThe `:only` option can also accept `Hash` arguments that we are considering deprecating.\n\n```ruby\nclass Article \u003C ActiveRecord::Base\n  has_paper_trail only: [{ title: Proc.new { |obj| !obj.title.blank? } }]\nend\n```\n\nIf the `title` is not blank, then only changes to the `title`\nwill create a version record.\n\n```ruby\na = Article.create\na.versions.length                         # 1\na.update content: 'Hello'\na.versions.length                         # 2\na.update title: 'Title One'\na.versions.length                         # 3\na.update content: 'Hai'\na.versions.length                         # 3\na.paper_trail.previous_version.content    # \"Hello\"\na.update title: 'Title Two'\na.versions.length                         # 4\na.paper_trail.previous_version.content    # \"Hai\"\n```\n\nConfiguring both `:ignore` and `:only` is not recommended, but it should work as\nexpected. Passing both `:ignore` and `:only` options will result in the\narticle being saved if a changed attribute is included in `:only` but not in\n`:ignore`.\n\n#### Skip\n\nIf you never want a field's values in the versions table, you can `:skip` the attribute.  As with `:ignore`,\nupdates to these attributes will not create a version record.  In addition, if a\nversion record is created for some other reason, these attributes will not be\npersisted.\n\n```ruby\nclass Author \u003C ActiveRecord::Base\n  has_paper_trail skip: [:social_security_number]\nend\n```\n\nAuthor's social security numbers will never appear in the versions log, and if an author updates only their social security number, it won't create a version record.\n\n#### Comparing `:ignore`, `:only`, and `:skip`\n\n- `:only` is basically the same as `:ignore`, but its inverse.\n- `:ignore` controls whether paper_trail will create a version record or not.\n- `:skip` controls whether paper_trail will save that field with the version record.\n- Skipped fields are also implicitly ignored. paper_trail does this internally.\n- Ignored fields are not implicitly skipped.\n\nSo:\n- Ignore a field if you don't want a version record created when it's the only field to change.\n- Skip a field if you don't want it to be saved with any version records.\n\n### 2.d. Turning PaperTrail Off\n\nPaperTrail is on by default, but sometimes you don't want to record versions.\n\n#### Per Process\n\nTurn PaperTrail off for **all threads** in a `ruby` process.\n\n```ruby\nPaperTrail.enabled = false\n```\n\n**Do not use this in production** unless you have a good understanding of\nthreads vs. processes.\n\nA legitimate use case is to speed up tests. See [Testing](#7-testing) below.\n\n#### Per HTTP Request\n\n```ruby\nPaperTrail.request(enabled: false) do\n  # no versions created\nend\n```\n\nor,\n\n```ruby\nPaperTrail.request.enabled = false\n# no versions created\nPaperTrail.request.enabled = true\n```\n\n#### Per Class\n\nIn the rare case that you need to disable versioning for one model while\nkeeping versioning enabled for other models, use:\n\n```ruby\nPaperTrail.request.disable_model(Banana)\n# changes to Banana model do not create versions,\n# but eg. changes to Kiwi model do.\nPaperTrail.request.enable_model(Banana)\nPaperTrail.request.enabled_for_model?(Banana) # => true\n```\n\nThis setting, as with all `PaperTrail.request` settings, affects only the\ncurrent request, not all threads.\n\nFor this rare use case, there is no convenient way to pass a block.\n\n##### In a Rails Controller Callback (Not Recommended)\n\nPaperTrail installs a callback in your rails controllers. The installed\ncallback will call `paper_trail_enabled_for_controller`, which you can\noverride.\n\n```ruby\nclass ApplicationController \u003C ActionController::Base\n  def paper_trail_enabled_for_controller\n    # Don't omit `super` without a good reason.\n    super && request.user_agent != 'Disable User-Agent'\n  end\nend\n```\n\nBecause you are unable to control the order of callback execution, this\ntechnique is not recommended, but is preserved for backwards compatibility.\n\nIt would be better to install your own callback and use\n`PaperTrail.request.enabled=` as you see fit.\n\n#### Per Method (Removed)\n\nThe `widget.paper_trail.without_versioning` method was removed in v10, without\nan exact replacement. To disable versioning, use the [Per Class](#per-class) or\n[Per HTTP Request](#per-http-request) methods.\n\n### 2.e. Limiting the Number of Versions Created\n\nConfigure `version_limit` to cap the number of versions saved per record. This\ndoes not apply to `create` events.\n\n```ruby\n# Limit: 4 versions per record (3 most recent, plus a `create` event)\nPaperTrail.config.version_limit = 3\n# Remove the limit\nPaperTrail.config.version_limit = nil\n```\n\n#### 2.e.1 Per-model limit\n\nModels can override the global `PaperTrail.config.version_limit` setting.\n\nExample:\n\n```\n# initializer\nPaperTrail.config.version_limit = 10\n\n# At most 10 versions\nhas_paper_trail\n\n# At most 3 versions (2 updates, 1 create). Overrides global version_limit.\nhas_paper_trail limit: 2\n\n# Infinite versions\nhas_paper_trail limit: nil\n```\n\n## 3. Working With Versions\n\n### 3.a. Reverting And Undeleting A Model\n\nPaperTrail makes reverting to a previous version easy:\n\n```ruby\nwidget = Widget.find 42\nwidget.update name: 'Blah blah'\n# Time passes....\nwidget = widget.paper_trail.previous_version  # the widget as it was before the update\nwidget.save                                   # reverted\n```\n\nAlternatively you can find the version at a given time:\n\n```ruby\nwidget = widget.paper_trail.version_at(1.day.ago)  # the widget as it was one day ago\nwidget.save                                        # reverted\n```\n\nNote `version_at` gives you the object, not a version, so you don't need to call\n`reify`.\n\nUndeleting is just as simple:\n\n```ruby\nwidget = Widget.find(42)\nwidget.destroy\n# Time passes....\nwidget = Widget.new(id:42)    # creating a new object with the same id, re-establishes the link\nversions = widget.versions    # versions ordered by versions.created_at, ascending\nwidget = versions.last.reify  # the widget as it was before destruction\nwidget.save                   # the widget lives!\n```\n\nYou could even use PaperTrail to implement an undo system; [Ryan Bates has!][3]\n\nIf your model uses [optimistic locking][1] don't forget to [increment your\n`lock_version`][2] before saving or you'll get a `StaleObjectError`.\n\n### 3.b. Navigating Versions\n\nYou can call `previous_version` and `next_version` on an item to get it as it\nwas\u002Fbecame.  Note that these methods reify the item for you.\n\n```ruby\nlive_widget = Widget.find 42\nlive_widget.versions.length                       # 4, for example\nwidget = live_widget.paper_trail.previous_version # => widget == live_widget.versions.last.reify\nwidget = widget.paper_trail.previous_version      # => widget == live_widget.versions[-2].reify\nwidget = widget.paper_trail.next_version          # => widget == live_widget.versions.last.reify\nwidget.paper_trail.next_version                   # live_widget\n```\n\nIf instead you have a particular `version` of an item you can navigate to the\nprevious and next versions.\n\n```ruby\nwidget = Widget.find 42\nversion = widget.versions[-2]    # assuming widget has several versions\nprevious_version = version.previous\nnext_version = version.next\n```\n\nYou can find out which of an item's versions yours is:\n\n```ruby\ncurrent_version_number = version.index    # 0-based\n```\n\nIf you got an item by reifying one of its versions, you can navigate back to the\nversion it came from:\n\n```ruby\nlatest_version = Widget.find(42).versions.last\nwidget = latest_version.reify\nwidget.version == latest_version    # true\n```\n\nYou can find out whether a model instance is the current, live one -- or whether\nit came instead from a previous version -- with `live?`:\n\n```ruby\nwidget = Widget.find 42\nwidget.paper_trail.live?            # true\nwidget = widget.paper_trail.previous_version\nwidget.paper_trail.live?            # false\n```\n\nSee also: Section 3.e. Queries\n\n### 3.c. Diffing Versions\n\nThere are two scenarios: diffing adjacent versions and diffing non-adjacent\nversions.\n\nThe best way to diff adjacent versions is to get PaperTrail to do it for you. If\nyou add an `object_changes` column to your `versions` table, PaperTrail will\nstore the `changes` diff in each version. Ignored attributes are omitted.\n\n```ruby\nwidget = Widget.create name: 'Bob'\nwidget.versions.last.changeset # reads object_changes column\n# {\n#   \"name\"=>[nil, \"Bob\"],\n#   \"created_at\"=>[nil, 2015-08-10 04:10:40 UTC],\n#   \"updated_at\"=>[nil, 2015-08-10 04:10:40 UTC],\n#   \"id\"=>[nil, 1]\n# }\nwidget.update name: 'Robert'\nwidget.versions.last.changeset\n# {\n#   \"name\"=>[\"Bob\", \"Robert\"],\n#   \"updated_at\"=>[2015-08-10 04:13:19 UTC, 2015-08-10 04:13:19 UTC]\n# }\nwidget.destroy\nwidget.versions.last.changeset\n# {}\n```\n\nPrior to 10.0.0, the `object_changes` were only stored for create and update\nevents. As of 10.0.0, they are stored for all three events.\n\nPaperTrail doesn't use diffs internally.\n\n> When I designed PaperTrail I wanted simplicity and robustness so I decided to\n> make each version of an object self-contained.  A version stores all of its\n> object's data, not a diff from the previous version.  This means you can\n> delete any version without affecting any other. -Andy\n\nTo diff non-adjacent versions you'll have to write your own code.  These\nlibraries may help:\n\nFor diffing two strings:\n\n* [htmldiff][19]: expects but doesn't require HTML input and produces HTML\n  output.  Works very well but slows down significantly on large (e.g. 5,000\n  word) inputs.\n* [differ][20]: expects plain text input and produces plain\n  text\u002Fcoloured\u002FHTML\u002Fany output.  Can do character-wise, word-wise, line-wise,\n  or arbitrary-boundary-string-wise diffs.  Works very well on non-HTML input.\n* [diff-lcs][21]: old-school, line-wise diffs.\n\nUnfortunately, there is no currently widely available and supported library for diffing two ActiveRecord objects.\n\n### 3.d. Deleting Old Versions\n\nOver time your `versions` table will grow to an unwieldy size.  Because each\nversion is self-contained (see the Diffing section above for more) you can\nsimply delete any records you don't want any more.  For example:\n\n```sql\nsql> delete from versions where created_at \u003C '2010-06-01';\n```\n\n```ruby\nPaperTrail::Version.where('created_at \u003C ?', 1.day.ago).delete_all\n```\n\n### 3.e. Queries\n\nYou can query records in the `versions` table based on their `object` or\n`object_changes` columns.\n\n```ruby\n# Find versions that meet these criteria.\nPaperTrail::Version.where_object(content: 'Hello', title: 'Article')\n\n# Find versions before and after attribute `atr` had value `v`:\nPaperTrail::Version.where_object_changes(atr: 'v')\n```\n\nSee also:\n\n- `where_object_changes_from`\n- `where_object_changes_to`\n- `where_attribute_changes`\n\nOnly `where_object` supports text columns. Your `object_changes` column should\nbe a `json` or `jsonb` column if possible. If you must use a `text` column,\nyou'll have to write a [custom\n`object_changes_adapter`](#6c-custom-object-changes).\n\n### 3.f. Defunct `item_id`s\n\nThe `item_id`s in your `versions` table can become defunct over time,\npotentially causing application errors when `id`s in the foreign table are\nreused. `id` reuse can be an explicit choice of the application, or implicitly\ncaused by sequence cycling. The chance of `id` reuse is reduced (but not\neliminated) with `bigint` `id`s or `uuid`s, `no cycle`\n[sequences](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fsql-createsequence.html),\nand\u002For when `versions` are periodically deleted.\n\nIdeally, a Foreign Key Constraint (FKC) would set `item_id` to null when an item\nis deleted. However, `items` is a polymorphic relationship. A partial FKC (e.g.\nan FKC with a `where` clause) is possible, but only in Postgres, and it is\nimpractical to maintain FKCs for every versioned table unless the number of\nsuch tables is very small.\n\nIf [per-table `Version`\nclasses](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail#6a-custom-version-classes)\nare used, then a partial FKC is no longer needed. So, a normal FKC can be\nwritten in any RDBMS, but it remains impractical to maintain so many FKCs.\n\nSome applications choose to handle this problem by \"soft-deleting\" versioned\nrecords, i.e. marking them as deleted instead of actually deleting them. This\ncompletely prevents `id` reuse, but adds complexity to the application. In most\napplications, this is the only known practical solution to the `id` reuse\nproblem.\n\n## 4. Saving More Information About Versions\n\n### 4.a. Finding Out Who Was Responsible For A Change\n\nSet `PaperTrail.request.whodunnit=`, and that value will be stored in the\nversion's `whodunnit` column.\n\n```ruby\nPaperTrail.request.whodunnit = 'Andy Stewart'\nwidget.update name: 'Wibble'\nwidget.versions.last.whodunnit # Andy Stewart\n```\n\n#### Setting `whodunnit` to a `Proc`\n\n`whodunnit=` also accepts a `Proc`, in the rare case that lazy evaluation is\nrequired.\n\n```ruby\nPaperTrail.request.whodunnit = proc do\n  caller.find { |c| c.starts_with? Rails.root.to_s }\nend\n```\n\nBecause lazy evaluation can be hard to troubleshoot, this is not\nrecommended for common use.\n\n#### Setting `whodunnit` Temporarily\n\nTo set whodunnit temporarily, for the duration of a block, use\n`PaperTrail.request`:\n\n```ruby\nPaperTrail.request(whodunnit: 'Dorian Marié') do\n  widget.update name: 'Wibble'\nend\n```\n\n#### Setting `whodunnit` with a controller callback\n\nIf your controller has a `current_user` method, PaperTrail provides a\ncallback that will assign `current_user.id` to `whodunnit`.\n\n```ruby\nclass ApplicationController\n  before_action :set_paper_trail_whodunnit\nend\n```\n\nYou may want `set_paper_trail_whodunnit` to call a different method to find out\nwho is responsible. To do so, override the `user_for_paper_trail` method in\nyour controller like this:\n\n```ruby\nclass ApplicationController\n  def user_for_paper_trail\n    logged_in? ? current_member.id : 'Public user'  # or whatever\n  end\nend\n```\n\nSee also: [Setting whodunnit in the rails console][33]\n\n#### Terminator and Originator\n\nA version's `whodunnit` column tells us who changed the object, causing the\n`version` to be stored.  Because a version stores the object as it looked before\nthe change (see the table above), `whodunnit` tells us who *stopped* the object\nlooking like this -- not who made it look like this.  Hence `whodunnit` is\naliased as `terminator`.\n\nTo find out who made a version's object look that way, use\n`version.paper_trail_originator`.  And to find out who made a \"live\" object look\nlike it does, call `paper_trail_originator` on the object.\n\n```ruby\nwidget = Widget.find 153                    # assume widget has 0 versions\nPaperTrail.request.whodunnit = 'Alice'\nwidget.update name: 'Yankee'\nwidget.paper_trail.originator               # 'Alice'\nPaperTrail.request.whodunnit = 'Bob'\nwidget.update name: 'Zulu'\nwidget.paper_trail.originator               # 'Bob'\nfirst_version, last_version = widget.versions.first, widget.versions.last\nfirst_version.whodunnit                     # 'Alice'\nfirst_version.paper_trail_originator        # nil\nfirst_version.terminator                    # 'Alice'\nlast_version.whodunnit                      # 'Bob'\nlast_version.paper_trail_originator         # 'Alice'\nlast_version.terminator                     # 'Bob'\n```\n\n#### Storing an ActiveRecord globalid in whodunnit\n\nIf you would like `whodunnit` to return an `ActiveRecord` object instead of a\nstring, please try the [paper_trail-globalid][37] gem.\n\n### 4.b. Associations\n\nTo track and reify associations, use [paper_trail-association_tracking][6] (PT-AT).\n\nFrom 2014 to 2018, association tracking was an experimental feature, but many\nissues were discovered. To attract new volunteers to address these issues, PT-AT\nwas extracted (see https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fissues\u002F1070).\n\nEven though it had always been an experimental feature, we didn't want the\nextraction of PT-AT to be a breaking change, so great care was taken to remove\nit slowly.\n\n- In PT 9, PT-AT was kept as a runtime dependency.\n- In PT 10, it became a development dependency (If you use it you must add it to\n  your own `Gemfile`) and we kept running all of its tests.\n- In PT 11, it will no longer be a development dependency, and it is responsible\n  for its own tests.\n\n#### 4.b.1 The optional `item_subtype` column\n\nAs of PT 10, users may add an `item_subtype` column to their `versions` table.\nWhen storing versions for STI models, rails stores the base class in `item_type`\n(that's just how polymorphic associations like `item` work) In addition, PT will\nnow store the subclass in `item_subtype`. If this column is present PT-AT will\nuse it to fix a rare issue with reification of STI subclasses.\n\n```ruby\nadd_column :versions, :item_subtype, :string, null: true\n```\n\nSo, if you use PT-AT and STI, the addition of this column is recommended.\n\n- https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fissues\u002F594\n- https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fpull\u002F1143\n- https:\u002F\u002Fgithub.com\u002Fwestonganger\u002Fpaper_trail-association_tracking\u002Fpull\u002F5\n\n### 4.c. Storing Metadata\n\nYou can add your own custom columns to your `versions` table. Values can be\ngiven using **Model Metadata** or **Controller Metadata**.\n\n#### Model Metadata\n\nYou can specify metadata in the model using `has_paper_trail(meta:)`.\n\n```ruby\nclass Article \u003C ActiveRecord::Base\n  belongs_to :author\n  has_paper_trail(\n    meta: {\n      author_id: :author_id, # model attribute\n      word_count: :count_words, # arbitrary model method\n      answer: 42, # scalar value\n      editor: proc { |article| article.editor.full_name } # a Proc\n    }\n  )\n  def count_words\n    153\n  end\nend\n```\n\n#### Metadata from Controllers\n\nYou can also store any information you like from your controller.  Override\nthe `info_for_paper_trail` method in your controller to return a hash whose keys\ncorrespond to columns in your `versions` table.\n\n```ruby\nclass ApplicationController\n  def info_for_paper_trail\n    { ip: request.remote_ip, user_agent: request.user_agent }\n  end\nend\n```\n\n#### Advantages of Metadata\n\nWhy would you do this?  In this example, `author_id` is an attribute of\n`Article` and PaperTrail will store it anyway in a serialized form in the\n`object` column of the `version` record.  But let's say you wanted to pull out\nall versions for a particular author; without the metadata you would have to\ndeserialize (reify) each `version` object to see if belonged to the author in\nquestion.  Clearly this is inefficient.  Using the metadata you can find just\nthose versions you want:\n\n```ruby\nPaperTrail::Version.where(author_id: author_id)\n```\n\n#### Metadata can Override PaperTrail Columns\n\n**Experts only**. Metadata will override the normal values that PT would have\ninserted into its own columns.\n\n| *PT Column*    | *How bad of an idea?* | *Alternative*                 |\n|----------------|-----------------------|-------------------------------|\n| created_at     | forbidden*            |                               |\n| event          | meh                   | paper_trail_event             |\n| id             | forbidden             |                               |\n| item_id        | forbidden             |                               |\n| item_subtype   | forbidden             |                               |\n| item_type      | forbidden             |                               |\n| object         | a little dangerous    |                               |\n| object_changes | a little dangerous    |                               |\n| updated_at     | forbidden             |                               |\n| whodunnit      | meh                   | PaperTrail.request.whodunnit= |\n\n\\* forbidden - raises a `PaperTrail::InvalidOption` error as of PT 14\n\n## 5. ActiveRecord\n\n### 5.a. Single Table Inheritance (STI)\n\nPaperTrail supports [Single Table Inheritance][39], and even supports an\nun-versioned base model, as of `23ffbdc7e1`.\n\n```ruby\nclass Fruit \u003C ActiveRecord::Base\n  # un-versioned base model\nend\nclass Banana \u003C Fruit\n  has_paper_trail\nend\n```\n\nHowever, there is a known issue when reifying [associations](#associations),\nsee https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fissues\u002F594\n\n### 5.b. Configuring the `versions` Association\n\n#### 5.b.1. `versions` association\n\nYou may configure the name of the `versions` association by passing a different\nname (default is `:versions`) in the `versions:` options hash:\n\n```ruby\nclass Post \u003C ActiveRecord::Base\n  has_paper_trail versions: {\n    name: :drafts\n  }\nend\n\nPost.new.versions # => NoMethodError\n```\n\nYou may pass a\n[scope](https:\u002F\u002Fapi.rubyonrails.org\u002Fclasses\u002FActiveRecord\u002FAssociations\u002FClassMethods.html#method-i-has_many-label-Scopes)\nto the `versions` association with the `scope:` option:\n```ruby\nclass Post \u003C ActiveRecord::Base\n  has_paper_trail versions: {\n    scope: -> { order(\"id desc\") }\n  }\n\n  # Equivalent to:\n  has_many :versions,\n    -> { order(\"id desc\") },\n    class_name: 'PaperTrail::Version',\n    as: :item\nend\n```\n\nAny other [options supported by\n`has_many`](https:\u002F\u002Fapi.rubyonrails.org\u002Fclasses\u002FActiveRecord\u002FAssociations\u002FClassMethods.html#method-i-has_many-label-Options)\ncan be passed along to the `has_many` macro via the `versions:` options hash.\n\n```ruby\nclass Post \u003C ActiveRecord::Base\n  has_paper_trail versions: {\n    extend: VersionsExtensions,\n    autosave: false\n  }\nend\n```\n\nOverriding (instead of configuring) the `versions` method is not supported.\nOverriding associations is not recommended in general.\n\n#### 5.b.2. `item` association\n\nA `PaperTrail::Version` object `belongs_to` an `item`, the relevant record.\n\nThe `item` association is first defined in `PaperTrail::VersionConcern`, but\nassociations can be redefined.\n\n##### Example: adding a `counter_cache` to `item` association\n\n```ruby\n# app\u002Fmodels\u002Fpaper_trail\u002Fversion.rb\nmodule PaperTrail\n  class Version \u003C ActiveRecord::Base\n    belongs_to :item, polymorphic: true, counter_cache: true\n  end\nend\n```\n\nWhen redefining an association, its options are _replaced_ not _merged_, so\ndon't forget to specify the options from `PaperTrail::VersionConcern`, like\n`polymorphic`.\n\nBe advised that redefining an association is an undocumented feature of Rails.\n\n### 5.c. Generators\n\nPaperTrail has one generator, `paper_trail:install`. It writes, but does not\nrun, a migration file. The migration creates the `versions` table.\n\nYou can provide a custom version table name e.g., for having multiple version tables. You will still need setup a custom Version class and configure it to use the custom table. See [6.a. Custom Version Classes](#6a-custom-version-classes).\n\n#### Reference\n\nThe most up-to-date documentation for this generator can be found by running\n`rails generate paper_trail:install --help`, but a copy is included here for\nconvenience.\n\n```\nUsage:\n  bin\u002Frails generate paper_trail:install [VERSION_CLASS_NAME] [options]\n\nOptions:\n  [--skip-namespace]                                            # Skip namespace (affects only isolated engines)\n                                                                # Default: false\n  [--skip-collision-check]                                      # Skip collision check\n                                                                # Default: false\n  [--with-changes], [--no-with-changes], [--skip-with-changes]  # Store changeset (diff) with each version\n                                                                # Default: false\n  [--uuid], [--no-uuid], [--skip-uuid]                          # Use uuid instead of bigint for item_id type (use only if tables use UUIDs)\n                                                                # Default: false\n\nRuntime options:\n  -f, [--force]                                      # Overwrite files that already exist\n  -p, [--pretend], [--no-pretend], [--skip-pretend]  # Run but do not make any changes\n  -q, [--quiet], [--no-quiet], [--skip-quiet]        # Suppress status output\n  -s, [--skip], [--no-skip], [--skip-skip]           # Skip files that already exist\n\nGenerates (but does not run) a migration to add a versions table. Can be customized by providing a Version class name. See section 5.c. Generators in README.md for more information.\n```\n\n### 5.d. Protected Attributes\n\nAs of version 6, PT no longer supports rails 3 or the [protected_attributes][17]\ngem. If you are still using them, you may use PT 5 or lower. We recommend\nupgrading to [strong_parameters][18] as soon as possible.\n\nIf you must use [protected_attributes][17] for now, and want to use PT > 5, you\ncan reopen `PaperTrail::Version` and add the following `attr_accessible` fields:\n\n```ruby\n# app\u002Fmodels\u002Fpaper_trail\u002Fversion.rb\nmodule PaperTrail\n  class Version \u003C ActiveRecord::Base\n    include PaperTrail::VersionConcern\n    attr_accessible :item_type, :item_id, :event, :whodunnit, :object, :object_changes, :created_at\n  end\nend\n```\n\nThis *unsupported workaround* has been tested with protected_attributes 1.0.9 \u002F\nrails 4.2.8 \u002F paper_trail 7.0.3.\n\n## 6. Extensibility\n\n### 6.a. Custom Version Classes\n\nYou can specify custom version subclasses with the `:class_name` option:\n\n```ruby\nclass PostVersion \u003C PaperTrail::Version\n  # custom behaviour, e.g:\n  self.table_name = :post_versions\nend\n\nclass Post \u003C ActiveRecord::Base\n  has_paper_trail versions: {\n    class_name: 'PostVersion'\n  }\nend\n```\n\nUnlike ActiveRecord's `class_name`, you'll have to supply the complete module\npath to the class (e.g. `Foo::BarVersion` if your class is inside the module\n`Foo`).\n\n#### Advantages\n\n1. For models which have a lot of versions, storing each model's versions in a\n   separate table can improve the performance of certain database queries.\n1. Store different version [metadata](#4c-storing-metadata) for different models.\n\n#### Configuration\n\nIf you are using Postgres, you should also define the sequence that your custom\nversion class will use:\n\n```ruby\nclass PostVersion \u003C PaperTrail::Version\n  self.table_name = :post_versions\n  self.sequence_name = :post_versions_id_seq\nend\n```\n\nIf you only use custom version classes and don't have a `versions` table, you must\nlet ActiveRecord know that your base version class (eg. `ApplicationVersion` below)\nclass is an `abstract_class`.\n\n```ruby\n# app\u002Fmodels\u002Fapplication_version.rb\nclass ApplicationVersion \u003C ActiveRecord::Base\n  include PaperTrail::VersionConcern\n  self.abstract_class = true\nend\n\nclass PostVersion \u003C ApplicationVersion\n  self.table_name = :post_versions\n  self.sequence_name = :post_versions_id_seq\nend\n```\n\nYou can also specify custom names for the versions and version associations.\nThis is useful if you already have `versions` or\u002Fand `version` methods on your\nmodel.  For example:\n\n```ruby\nclass Post \u003C ActiveRecord::Base\n  has_paper_trail versions: { name: :paper_trail_versions },\n                  version:          :paper_trail_version\n\n  # Existing versions method.  We don't want to clash.\n  def versions\n    # ...\n  end\n\n  # Existing version method.  We don't want to clash.\n  def version\n    # ...\n  end\nend\n```\n\n### 6.b. Custom Serializer\n\nBy default, PaperTrail stores your changes as a `YAML` dump. You can override\nthis with the serializer config option:\n\n```ruby\nPaperTrail.serializer = MyCustomSerializer\n```\n\nA valid serializer is a `module` (or `class`) that defines a `load` and `dump`\nmethod.  These serializers are included in the gem for your convenience:\n\n* [PaperTrail::Serializers::YAML][24] - Default\n* [PaperTrail::Serializers::JSON][25]\n\n#### PostgreSQL JSON column type support\n\nIf you use PostgreSQL, and would like to store your `object` (and\u002For\n`object_changes`) data in a column of [type `json` or type `jsonb`][26], specify\n`json` instead of `text` for these columns in your migration:\n\n```ruby\ncreate_table :versions do |t|\n  # ...\n  t.json :object          # Full object changes\n  t.json :object_changes  # Optional column-level changes\n  # ...\nend\n```\n\nIf you use the PostgreSQL `json` or `jsonb` column type, you do not need\nto specify a `PaperTrail.serializer`.\n\n##### Convert existing YAML data to JSON\n\nIf you've been using PaperTrail for a while with the default YAML serializer\nand you want to switch to JSON or JSONB, you're in a bit of a bind because\nthere's no automatic way to migrate your data. The first (slow) option is to\nloop over every record and parse it in Ruby, then write to a temporary column:\n\n```ruby\nadd_column :versions, :new_object, :jsonb # or :json\n# add_column :versions, :new_object_changes, :jsonb # or :json\n\n# PaperTrail::Version.reset_column_information # needed for rails \u003C 6\n\nPaperTrail::Version.where.not(object: nil).find_each do |version|\n  version.update_column(:new_object, YAML.load(version.object))\n\n  # if version.object_changes\n  #   version.update_column(\n  #     :new_object_changes,\n  #     YAML.load(version.object_changes)\n  #   )\n  # end\nend\n\nremove_column :versions, :object\n# remove_column :versions, :object_changes\nrename_column :versions, :new_object, :object\n# rename_column :versions, :new_object_changes, :object_changes\n```\n\nThis technique can be very slow if you have a lot of data. Though slow, it is\nsafe in databases where transactions are protected against DDL, such as\nPostgres. In databases without such protection, such as MySQL, a table lock may\nbe necessary.\n\nIf the above technique is too slow for your needs, and you're okay doing without\nPaperTrail data temporarily, you can create the new column without converting\nthe data.\n\n```ruby\nrename_column :versions, :object, :old_object\nadd_column :versions, :object, :jsonb # or :json\n```\n\nAfter that migration, your historical data still exists as YAML, and new data\nwill be stored as JSON. Next, convert records from YAML to JSON using a\nbackground script.\n\n```ruby\nPaperTrail::Version.where.not(old_object: nil).find_each do |version|\n  version.update_columns old_object: nil, object: YAML.load(version.old_object)\nend\n```\n\nFinally, in another migration, remove the old column.\n\n```ruby\nremove_column :versions, :old_object\n```\n\nIf you use the optional `object_changes` column, don't forget to convert it\nalso, using the same technique.\n\n##### Convert a Column from Text to JSON\n\nIf your `object` column already contains JSON data, and you want to change its\ndata type to `json` or `jsonb`, you can use the following [DDL][36]. Of course,\nif your `object` column contains YAML, you must first convert the data to JSON\n(see above) before you can change the column type.\n\nUsing SQL:\n\n```sql\nalter table versions\nalter column object type jsonb\nusing object::jsonb;\n```\n\nUsing ActiveRecord:\n\n```ruby\nclass ConvertVersionsObjectToJson \u003C ActiveRecord::Migration\n  def up\n    change_column :versions, :object, 'jsonb USING object::jsonb'\n  end\n\n  def down\n    change_column :versions, :object, 'text USING object::text'\n  end\nend\n```\n\n### 6.c. Custom Object Changes\n\nTo fully control the contents of their `object_changes` column, expert users\ncan write an adapter.\n\n```ruby\nPaperTrail.config.object_changes_adapter = MyObjectChangesAdapter.new\n\nclass MyObjectChangesAdapter\n  # @param changes Hash\n  # @return Hash\n  def diff(changes)\n    # ...\n  end\nend\n```\n\nYou should only use this feature if you are comfortable reading PT's source to\nsee exactly how the adapter is used. For example, see how `diff` is used by\nreading `::PaperTrail::Events::Base#recordable_object_changes`.\n\nAn adapter can implement any or all of the following methods:\n\n1. diff: Returns the changeset in the desired format given the changeset in the\n  original format\n2. load_changeset: Returns the changeset for a given version object\n3. where_object_changes: Returns the records resulting from the given hash of\n  attributes.\n4. where_object_changes_from: Returns the records resulting from the given hash\n  of attributes where the attributes changed *from* the provided value(s).\n5. where_object_changes_to: Returns the records resulting from the given hash of\n  attributes where the attributes changed *to* the provided value(s).\n6. where_attribute_changes: Returns the records where the attribute changed to\n  or from any value.\n\nDepending on your needs, you may choose to implement only a subset of these\nmethods.\n\n#### Known Adapters\n\n- [paper_trail-hashdiff](https:\u002F\u002Fgithub.com\u002Fhashwin\u002Fpaper_trail-hashdiff)\n\n### 6.d. Excluding the Object Column\n\nThe `object` column ends up storing a lot of duplicate data if you have models that have many columns,\nand that are updated many times. You can save ~50% of storage space by removing the column from the\nversions table. It's important to note that this will disable `reify` and `where_object`.\n\n### 6.e. Error handling\n\nYou can change the behavior of error handling when an exception is raised while creating a version, by setting the `version_error_behavior` option:\n\n```ruby\n# config\u002Finitializers\u002Fpaper_trail.rb\nPaperTrail.config.version_error_behavior = :legacy # (Default) Raise on create, log on update\u002Fdelete.\nPaperTrail.config.version_error_behavior = :log # Only log error.\nPaperTrail.config.version_error_behavior = :exception # Raise exception.\nPaperTrail.config.version_error_behavior = :silent # No-op.\n```\n\n## 7. Testing\n\nYou may want to turn PaperTrail off to speed up your tests.  See [Turning\nPaperTrail Off](#2d-turning-papertrail-off) above.\n\n### 7.a. Minitest\n\nFirst, disable PT for the entire `ruby` process.\n\n```ruby\n# in config\u002Fenvironments\u002Ftest.rb\nconfig.after_initialize do\n  PaperTrail.enabled = false\nend\n```\n\nThen, to enable PT for specific tests, you can add a `with_versioning` test\nhelper method.\n\n```ruby\n# in test\u002Ftest_helper.rb\ndef with_versioning\n  was_enabled = PaperTrail.enabled?\n  was_enabled_for_request = PaperTrail.request.enabled?\n  PaperTrail.enabled = true\n  PaperTrail.request.enabled = true\n  begin\n    yield\n  ensure\n    PaperTrail.enabled = was_enabled\n    PaperTrail.request.enabled = was_enabled_for_request\n  end\nend\n```\n\nThen, use the helper in your tests.\n\n```ruby\ntest 'something that needs versioning' do\n  with_versioning do\n    # your test\n  end\nend\n```\n\n### 7.b. RSpec\n\nPaperTrail provides a helper, `paper_trail\u002Fframeworks\u002Frspec.rb`, that works with\n[RSpec][27] to make it easier to control when `PaperTrail` is enabled during\ntesting.\n\n```ruby\n# spec\u002Frails_helper.rb\nENV[\"RAILS_ENV\"] ||= 'test'\nrequire 'spec_helper'\nrequire File.expand_path(\"..\u002F..\u002Fconfig\u002Fenvironment\", __FILE__)\nrequire 'rspec\u002Frails'\n# ...\nrequire 'paper_trail\u002Fframeworks\u002Frspec'\n```\n\nWith the helper loaded, PaperTrail will be turned off for all tests by\ndefault. To enable PaperTrail for a test you can either wrap the\ntest in a `with_versioning` block, or pass in `versioning: true` option to a\nspec block.\n\n```ruby\ndescribe 'RSpec test group' do\n  it 'by default, PaperTrail will be turned off' do\n    expect(PaperTrail).to_not be_enabled\n  end\n\n  with_versioning do\n    it 'within a `with_versioning` block it will be turned on' do\n      expect(PaperTrail).to be_enabled\n    end\n  end\n\n  it 'can be turned on at the `it` or `describe` level', versioning: true do\n    expect(PaperTrail).to be_enabled\n  end\nend\n```\n\nThe helper will also reset `whodunnit` to `nil` before each\ntest to help prevent data spillover between tests. If you are using PaperTrail\nwith Rails, the helper will automatically set the\n`PaperTrail.request.controller_info` value to `{}` as well, again, to help\nprevent data spillover between tests.\n\nThere is also a `be_versioned` matcher provided by PaperTrail's RSpec helper\nwhich can be leveraged like so:\n\n```ruby\nclass Widget \u003C ActiveRecord::Base\nend\n\ndescribe Widget do\n  it 'is not versioned by default' do\n    is_expected.to_not be_versioned\n  end\n\n  describe 'add versioning to the `Widget` class' do\n    before(:all) do\n      class Widget \u003C ActiveRecord::Base\n        has_paper_trail\n      end\n    end\n\n    it 'enables paper trail' do\n      is_expected.to be_versioned\n    end\n  end\nend\n```\n\n#### Matchers\n\nThe `have_a_version_with` matcher makes assertions about versions using\n`where_object`, based on the `object` column.\n\n```ruby\ndescribe '`have_a_version_with` matcher' do\n  it 'is possible to do assertions on version attributes' do\n    widget.update!(name: 'Leonard', an_integer: 1)\n    widget.update!(name: 'Tom')\n    widget.update!(name: 'Bob')\n    expect(widget).to have_a_version_with name: 'Leonard', an_integer: 1\n    expect(widget).to have_a_version_with an_integer: 1\n    expect(widget).to have_a_version_with name: 'Tom'\n  end\nend\n```\n\nThe `have_a_version_with_changes` matcher makes assertions about versions using\n`where_object_changes`, based on the optional\n[`object_changes` column](#3c-diffing-versions).\n\n```ruby\ndescribe '`have_a_version_with_changes` matcher' do\n  it 'is possible to do assertions on version changes' do\n    widget.update!(name: 'Leonard', an_integer: 1)\n    widget.update!(name: 'Tom')\n    widget.update!(name: 'Bob')\n    expect(widget).to have_a_version_with_changes name: 'Leonard', an_integer: 2\n    expect(widget).to have_a_version_with_changes an_integer: 2\n    expect(widget).to have_a_version_with_changes name: 'Bob'\n  end\nend\n```\n\nFor more examples of the RSpec matchers, see the\n[Widget spec](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fmaster\u002Fspec\u002Fmodels\u002Fwidget_spec.rb)\n\n### 7.c. Cucumber\n\nPaperTrail provides a helper for [Cucumber][28] that works similar to the RSpec\nhelper. If you want to use the helper, you will need to require in your cucumber\nhelper like so:\n\n```ruby\n# features\u002Fsupport\u002Fenv.rb\n\nENV[\"RAILS_ENV\"] ||= 'cucumber'\nrequire File.expand_path(File.dirname(__FILE__) + '\u002F..\u002F..\u002Fconfig\u002Fenvironment')\n# ...\nrequire 'paper_trail\u002Fframeworks\u002Fcucumber'\n```\n\nWhen the helper is loaded, PaperTrail will be turned off for all scenarios by a\n`before` hook added by the helper by default. When you want to enable PaperTrail\nfor a scenario, you can wrap code in a `with_versioning` block in a step, like\nso:\n\n```ruby\nGiven \u002FI want versioning on my model\u002F do\n  with_versioning do\n    # PaperTrail will be turned on for all code inside of this block\n  end\nend\n```\n\nThe helper will also reset the `whodunnit` value to `nil` before each\ntest to help prevent data spillover between tests. If you are using PaperTrail\nwith Rails, the helper will automatically set the\n`PaperTrail.request.controller_info` value to `{}` as well, again, to help\nprevent data spillover between tests.\n\n### 7.d. Spork\n\nIf you want to use the `RSpec` or `Cucumber` helpers with [Spork][29], you will\nneed to manually require the helper(s) in your `prefork` block on your test\nhelper, like so:\n\n```ruby\n# spec\u002Frails_helper.rb\n\nrequire 'spork'\n\nSpork.prefork do\n  # This file is copied to spec\u002F when you run 'rails generate rspec:install'\n  ENV[\"RAILS_ENV\"] ||= 'test'\n  require 'spec_helper'\n  require File.expand_path(\"..\u002F..\u002Fconfig\u002Fenvironment\", __FILE__)\n  require 'rspec\u002Frails'\n  require 'paper_trail\u002Fframeworks\u002Frspec'\n  require 'paper_trail\u002Fframeworks\u002Fcucumber'\n  # ...\nend\n```\n\n### 7.e. Zeus or Spring\n\nIf you want to use the `RSpec` or `Cucumber` helpers with [Zeus][30] or\n[Spring][31], you will need to manually require the helper(s) in your test\nhelper, like so:\n\n```ruby\n# spec\u002Frails_helper.rb\n\nENV[\"RAILS_ENV\"] ||= 'test'\nrequire 'spec_helper'\nrequire File.expand_path(\"..\u002F..\u002Fconfig\u002Fenvironment\", __FILE__)\nrequire 'rspec\u002Frails'\nrequire 'paper_trail\u002Fframeworks\u002Frspec'\n```\n\n## 8. PaperTrail Plugins\n\n- paper_trail-active_record\n- [paper_trail-association_tracking][6] - track and reify associations\n- paper_trail-audit\n- paper_trail-background\n- [paper_trail-globalid][49] - enhances whodunnit by adding an `actor`\n- paper_trail-hashdiff\n- paper_trail-rails\n- paper_trail-related_changes\n- paper_trail-sinatra\n- paper_trail_actor\n- paper_trail_changes\n- paper_trail_manager\n- paper_trail_scrapbook\n- paper_trail_ui\n- revertible_paper_trail\n- rspec-paper_trail\n- sequel_paper_trail\n\n## 9. Integration with Other Libraries\n\n- [ActiveAdmin][42]\n- [paper_trail_manager][46] - Browse, subscribe, view and revert changes to\n  records with rails and paper_trail\n- [rails_admin_history_rollback][51] - History rollback for rails_admin with PT\n- Sinatra - [paper_trail-sinatra][41]\n- [globalize][45] - [globalize-versioning][44]\n- [solidus_papertrail][47] - PT integration for Solidus\n  method to instances of PaperTrail::Version that returns the ActiveRecord\n  object who was responsible for change\n\n## 10. Related Libraries and Ports\n\n- [izelnakri\u002Fpaper_trail][50] - An Ecto library, inspired by PT.\n- [sequelize-paper-trail][48] - A JS library, inspired by PT. A sequelize\n  plugin for tracking revision history of model instances.\n\n## Articles\n\n* [PaperTrail Gem Tutorial](https:\u002F\u002Fstevepolito.design\u002Fblog\u002Fpaper-trail-gem-tutorial\u002F), 20th April 2020.\n* [Jutsu #8 - Version your RoR models with PaperTrail](http:\u002F\u002Fsamurails.com\u002Fgems\u002Fpapertrail\u002F),\n  [Thibault](http:\u002F\u002Fsamurails.com\u002Fabout-me\u002F), 29th September 2014\n* [Versioning with PaperTrail](http:\u002F\u002Fwww.sitepoint.com\u002Fversioning-papertrail),\n  [Ilya Bodrov](http:\u002F\u002Fwww.sitepoint.com\u002Fauthor\u002Fibodrov), 10th April 2014\n* [Using PaperTrail to track stack traces](http:\u002F\u002Fweb.archive.org\u002Fweb\u002F20141120233916\u002Fhttp:\u002F\u002Frubyrailsexpert.com\u002F?p=36),\n  T James Corcoran's blog, 1st October 2013.\n* [RailsCast #255 - Undo with PaperTrail](http:\u002F\u002Frailscasts.com\u002Fepisodes\u002F255-undo-with-paper-trail),\n  28th February 2011.\n* [Keep a Paper Trail with PaperTrail](http:\u002F\u002Fwww.linux-mag.com\u002Fid\u002F7528),\n  Linux Magazine, 16th September 2009.\n\n## Problems\n\nPlease use GitHub's [issue tracker](https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fissues).\n\n## Contributors\n\nCreated by Andy Stewart in 2010, maintained since 2012 by Ben Atkins, since 2015\nby Jared Beck, with contributions by over 150 people.\n\nhttps:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fgraphs\u002Fcontributors\n\n## Contributing\n\nSee our [contribution guidelines][43]\n\n## Inspirations\n\n* [Simply Versioned](https:\u002F\u002Fgithub.com\u002Fjerome\u002Fsimply_versioned)\n* [Acts As Audited](https:\u002F\u002Fgithub.com\u002Fcollectiveidea\u002Faudited)\n\n## Intellectual Property\n\nCopyright (c) 2011 Andy Stewart (boss@airbladesoftware.com).\nReleased under the MIT licence.\n\n[1]: http:\u002F\u002Fapi.rubyonrails.org\u002Fclasses\u002FActiveRecord\u002FLocking\u002FOptimistic.html\n[2]: https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fissues\u002F163\n[3]: http:\u002F\u002Frailscasts.com\u002Fepisodes\u002F255-undo-with-paper-trail\n[4]: https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Factions\u002Fworkflows\u002Ftest.yml\u002Fbadge.svg\n[5]: https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Factions\u002Fworkflows\u002Ftest.yml\n[6]: https:\u002F\u002Fgithub.com\u002Fwestonganger\u002Fpaper_trail-association_tracking\n[9]: https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Ftree\u002F3.0-stable\n[10]: https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Ftree\u002F2.7-stable\n[11]: https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Ftree\u002Frails2\n[14]: https:\u002F\u002Fraw.github.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fmaster\u002Flib\u002Fgenerators\u002Fpaper_trail\u002Ftemplates\u002Fcreate_versions.rb\n[16]: https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fissues\u002F113\n[17]: https:\u002F\u002Fgithub.com\u002Frails\u002Fprotected_attributes\n[18]: https:\u002F\u002Fgithub.com\u002Frails\u002Fstrong_parameters\n[19]: http:\u002F\u002Fgithub.com\u002Fmyobie\u002Fhtmldiff\n[20]: http:\u002F\u002Fgithub.com\u002Fpvande\u002Fdiffer\n[21]: https:\u002F\u002Fgithub.com\u002Fhalostatue\u002Fdiff-lcs\n[24]: https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fmaster\u002Flib\u002Fpaper_trail\u002Fserializers\u002Fyaml.rb\n[25]: https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fmaster\u002Flib\u002Fpaper_trail\u002Fserializers\u002Fjson.rb\n[26]: http:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002F9.4\u002Fstatic\u002Fdatatype-json.html\n[27]: https:\u002F\u002Fgithub.com\u002Frspec\u002Frspec\n[28]: http:\u002F\u002Fcukes.info\n[29]: https:\u002F\u002Fgithub.com\u002Fsporkrb\u002Fspork\n[30]: https:\u002F\u002Fgithub.com\u002Fburke\u002Fzeus\n[31]: https:\u002F\u002Fgithub.com\u002Frails\u002Fspring\n[32]: http:\u002F\u002Fapi.rubyonrails.org\u002Fclasses\u002FActiveRecord\u002FAutosaveAssociation.html#method-i-mark_for_destruction\n[33]: https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fwiki\u002FSetting-whodunnit-in-the-rails-console\n[34]: https:\u002F\u002Fgithub.com\u002Frails\u002Frails\u002Fblob\u002F591a0bb87fff7583e01156696fbbf929d48d3e54\u002Factiverecord\u002Flib\u002Factive_record\u002Ffixtures.rb#L142\n[35]: https:\u002F\u002Fdev.mysql.com\u002Fdoc\u002Frefman\u002F5.6\u002Fen\u002Ffractional-seconds.html\n[36]: http:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002F9.4\u002Finteractive\u002Fddl.html\n[37]: https:\u002F\u002Fgithub.com\u002Fankit1910\u002Fpaper_trail-globalid\n[38]: https:\u002F\u002Fgithub.com\u002Fsferik\u002Frails_admin\n[39]: http:\u002F\u002Fapi.rubyonrails.org\u002Fclasses\u002FActiveRecord\u002FBase.html#class-ActiveRecord::Base-label-Single+table+inheritance\n[40]: http:\u002F\u002Fapi.rubyonrails.org\u002Fclasses\u002FActiveRecord\u002FAssociations\u002FClassMethods.html#module-ActiveRecord::Associations::ClassMethods-label-Polymorphic+Associations\n[41]: https:\u002F\u002Fgithub.com\u002Fjaredbeck\u002Fpaper_trail-sinatra\n[42]: https:\u002F\u002Fgithub.com\u002Factiveadmin\u002Factiveadmin\u002Fwiki\u002FAuditing-via-paper_trail-%28change-history%29\n[43]: https:\u002F\u002Fgithub.com\u002Fpaper-trail-gem\u002Fpaper_trail\u002Fblob\u002Fmaster\u002F.github\u002FCONTRIBUTING.md\n[44]: https:\u002F\u002Fgithub.com\u002Fglobalize\u002Fglobalize-versioning\n[45]: https:\u002F\u002Fgithub.com\u002Fglobalize\u002Fglobalize\n[46]: https:\u002F\u002Fgithub.com\u002Ffusion94\u002Fpaper_trail_manager\n[47]: https:\u002F\u002Fgithub.com\u002Fsolidusio-contrib\u002Fsolidus_papertrail\n[48]: https:\u002F\u002Fgithub.com\u002Fnielsgl\u002Fsequelize-paper-trail\n[49]: https:\u002F\u002Fgithub.com\u002Fankit1910\u002Fpaper_trail-globalid\n[50]: https:\u002F\u002Fgithub.com\u002Fizelnakri\u002Fpaper_trail\n[51]: https:\u002F\u002Fgithub.com\u002Frikkipitt\u002Frails_admin_history_rollback\n[52]: http:\u002F\u002Fguides.rubyonrails.org\u002Factive_record_callbacks.html\n[53]: https:\u002F\u002Fbadge.fury.io\u002Frb\u002Fpaper_trail.svg\n[54]: https:\u002F\u002Frubygems.org\u002Fgems\u002Fpaper_trail\n[55]:  https:\u002F\u002Fdependabot-badges.githubapp.com\u002Fbadges\u002Fcompatibility_score?dependency-name=paper_trail&package-manager=bundler&previous-version=15.2.0&new-version=16.0.0\n[56]: https:\u002F\u002Fdependabot.com\u002Fcompatibility-score.html?dependency-name=paper_trail&package-manager=bundler&version-scheme=semver\n[57]: https:\u002F\u002Fbundler.io\u002Fv2.3\u002Fman\u002Fbundle-install.1.html\n","PaperTrail 是一个用于跟踪 Rails 模型更改的 Ruby 宝石。它通过记录模型的每个变更版本，实现了审计和版本控制功能，允许用户查看模型在生命周期中任何阶段的状态、回滚到任一历史版本或恢复已删除的数据。该工具支持 ActiveRecord，并且能够灵活配置哪些属性以及何时需要被监控，从而满足不同场景下的需求。适用于需要对数据修改进行追踪的应用环境，如企业级应用开发中的日志记录、合规性检查等。",2,"2026-06-11 03:13:46","top_language"]