gitmyhub

paper_trail

Ruby ★ 7.0k updated 1mo ago

Track changes to your rails models

Ruby gem for Rails apps that automatically records every create, update, and delete on your database records, giving you a full change history you can browse, diff, or roll back at any time.

RubyRailssetup: easycomplexity 2/5

PaperTrail is a Ruby gem for Rails applications that records every change made to your database records. When someone creates, updates, or deletes a record, PaperTrail saves a snapshot of what the record looked like before the change. You can then look back at the full history of any record, see exactly what changed and when, and restore a previous state if needed. This is useful for audit logs, undoing mistakes, or simply understanding how data changed over time.

Setup involves three steps: adding the gem to your project, running a generator that creates a new database table called versions to store the history, and adding a single line to any model you want to track. After that, every tracked record gains a versions method that returns its full change history.

Each saved version tells you what event occurred (create, update, or destroy), when it happened, and optionally who triggered it. If your app has a logged-in user concept, a one-line addition to your base controller wires up automatic tracking of who made each change. To restore a record to a past state, you call reify on a version object, which reconstructs the record as it existed at that point in time.

You have fine-grained control over what gets tracked. You can choose to record only certain lifecycle events, skip tracking when specific conditions are met, include or exclude individual fields, or turn tracking off entirely for a block of code. There are also options to limit how many versions are kept, attach extra metadata to each version, and track changes to associated records.

PaperTrail is one of the longest-standing gems in the Rails ecosystem, with a version history stretching back to Rails 2.3. It follows semantic versioning and ships with test helpers for Minitest, RSpec, and Cucumber. The full README is longer than what was shown.

Where it fits