Screencast

23. Version history with PaperTrail and Ecto in LiveView

ecto liveview papertrail versions

How to Track Database Changes in Phoenix with PaperTrail

When you need to track every change made to your database records in Phoenix, PaperTrail provides a straightforward solution. It automatically captures who made the change, when it happened, and what exactly changed - perfect for audit trails and debugging complex issues.

def update_brewery(%Brewery{} = brewery, attrs) do
  brewery
  |> Brewery.changeset(attrs)
  |> Repo.update_with_papertrail()
end

Implementing Version History in Phoenix LiveView

Building a version history page in Phoenix LiveView becomes simple with PaperTrail. You can display a complete timeline of changes, allowing users to see exactly how data evolved over time. The versioning system automatically tracks all database operations, making it easy to build features like audit logs or change history views.

def get_versions(%schema{id: id}) do
  PaperTrail.get_versions(schema, id)
end

# In your LiveView template:
<%= for {key, value} <- version.item_changes do %>
  {Phoenix.Naming.humanize(key)}: {value}<br>
<% end %>

How to Revert Database Changes in Phoenix Applications

Need to roll back changes in your Phoenix application? PaperTrail makes it straightforward to revert to any previous version of a record. This is particularly useful when you need to undo accidental changes or provide users with the ability to restore previous versions of their data.

def revert_to_version(record, version_id) when is_struct(record) do
  versions = get_versions(record)
  attributes = changes_to_revert(versions, version_id)

  record
  |> Ecto.Changeset.change(attributes)
  |> PaperTrail.update(origin: "versions")
end