Ruby on Rails
Section titled “Ruby on Rails”View the integration on GitHub
PgStack Audit plugs into Ruby on Rails with Active Record and PostgreSQL to track database changes automatically. It supports audit trails with application context and historical queries in your application.
This Ruby gem passes application-specific context with database changes through the Ruby on Rails integration. Context can include the 'where' (API endpoint, worker, etc.), 'who' (user, cron job, etc.), and 'how' behind a change.
Prerequisites
Section titled “Prerequisites”- PostgreSQL 14+
- Ruby on Rails
Installation
Section titled “Installation”- Install the gem
gem 'bemi-rails'- Generate a Rails migration file to add lightweight PostgreSQL triggers for passing application context with all data changes into PostgreSQL replication log
bin/rails g bemi:migration- Run the rails migration
bin/rails db:migrateYou can specify custom application context that will be automatically passed with all data changes.
class ApplicationController < ActionController::Base before_action :set_bemi_context
private
def set_bemi_context Bemi.set_context( user_id: current_user&.id, endpoint: "#{request.method} #{request.path}", method: "#{self.class}##{action_name}", ) endendApplication context:
- Is bound to the current Ruby thread. So it is isolated to a single HTTP request or background job.
- Is used only with
INSERT,UPDATE,DELETESQL queries performed via Active Record. Otherwise, it is a no-op. - Is passed directly into PG Write-Ahead Log with data changes without affecting the structure of the database and SQL queries.
Application context will automatically include the original SQL query that performed data changes, which is generally useful for troubleshooting purposes.
Data change tracking
Section titled “Data change tracking”Connect your PostgreSQL database to PgStack Audit using the quickstart. Configure logical replication using the guide for your hosting platform.
With the integration installed, make a change through your application and check the project's Audit view. The change should include the application context supplied by your integration. Changes made outside the integrated application are still captured, but do not receive that application's context.
Use the PgStack database connection details from your project settings to query changes with SQL or your ORM. Replace [USERNAME], [HOSTNAME], and [DATABASE] with those details:
psql postgres://[USERNAME]@[HOSTNAME]:5432/[DATABASE] -c \ 'SELECT "primary_key", "table", "operation", "before", "after", "context", "committed_at" FROM changes;'Example output:
primary_key | table | operation | before | after | context | committed_at-------------+-------+-----------+----------------------------------------------------+-----------------------------------------------------+-------------------------------------------------------------------------------------------+------------------------ 26 | todo | CREATE | {} | {"id": 26, "task": "Sleep", "is_completed": false} | {"user_id": 187234, "endpoint": "/todo", "method": "POST", "SQL": "INSERT INTO ..."} | 2023-12-11 17:09:09+00 27 | todo | CREATE | {} | {"id": 27, "task": "Eat", "is_completed": false} | {"user_id": 187234, "endpoint": "/todo", "method": "POST", "SQL": "INSERT INTO ..."} | 2023-12-11 17:09:11+00 28 | todo | CREATE | {} | {"id": 28, "task": "Repeat", "is_completed": false} | {"user_id": 187234, "endpoint": "/todo", "method": "POST", "SQL": "INSERT INTO ..."} | 2023-12-11 17:09:13+00 26 | todo | UPDATE | {"id": 26, "task": "Sleep", "is_completed": false} | {"id": 26, "task": "Sleep", "is_completed": true} | {"user_id": 187234, "endpoint": "/todo/complete", "method": "PUT", "SQL": "UPDATE ..."} | 2023-12-11 17:09:15+00 27 | todo | DELETE | {"id": 27, "task": "Eat", "is_completed": false} | {} | {"user_id": 187234, "endpoint": "/todo/27", "method": "DELETE", "SQL": "DELETE FROM ..."} | 2023-12-11 17:09:18+00Data change querying
Section titled “Data change querying”Connect to the PgStack Audit PostgreSQL destination database to query change data from your application.
To query historical data, configure an additional database connection with Active Record:
production: primary: <<: *default # Your regular database settings go here pgstack: adapter: postgresql encoding: unicode pool: <%= ENV["RAILS_MAX_THREADS"] || 5 %> host: <%= ENV["DESTINATION_DB_HOST"] %> port: <%= ENV["DESTINATION_DB_PORT"] %> database: <%= ENV["DESTINATION_DB_DATABASE"] %> username: <%= ENV["DESTINATION_DB_USERNAME"] %> password: <%= ENV["DESTINATION_DB_PASSWORD"] %> migrations_paths: db/pgstack_migrateCreate a new model that connects to the destination database:
# frozen_string_literal: true
class BemiRecord < ApplicationRecord self.abstract_class = true connects_to database: { writing: :pgstack, reading: :pgstack }endCreate a new BemiChange model to access all data changes:
# frozen_string_literal: true
class BemiChange < BemiRecord include Bemi::ChangeQueryHelpers self.table_name = 'changes'endAdd a helper module to the tracked models or your main ApplicationRecord and set bemi_change_class:
class ApplicationRecord < ActiveRecord::Base include Bemi::RecordQueryHelpers bemi_change_class 'BemiChange' # ...endQuery changes
Section titled “Query changes”BemiChange.take# => #<BemiChange:0x000000012f7fab40# id: "fe85c5e2-489c-4172-83dd-b58f25edb412",# committed_at: Tue, 25 Apr 2024 22:15:50.890000000 UTC +00:00,# table: "todos",# primary_key: "27",# operation: "UPDATE",# before: {"id"=>27, "task"=>"Walk", "is_completed"=>false}># after: {"id"=>27, "task"=>"Run", "is_completed"=>true},# context:# {"SQL"=> "UPDATE \"public\".\"todos\" SET \"task\" = $1, \"is_completed\" = $2 WHERE \"public\".\"todos\".\"id\" = $3",# "user_id"=>1,# "api_endpoint"=>"/todos/complete"},# ...Diff changed values
Section titled “Diff changed values”BemiChange.take.diff# => { "task" => ["Walk", "Run"], "completed" => [false, true] }Query change by record
Section titled “Query change by record”record = Todo.find(...)record.bemi_changes.limit(10)Filter by values
Section titled “Filter by values”# Query by the previous valuesrecord.bemi_changes.before(task: 'Walk')record.bemi_changes.before(task: 'Walk', completed: false)record.bemi_changes.before_not(task: 'Run')
# Query by the new valuesrecord.bemi_changes.after(task: 'Run')record.bemi_changes.after(task: 'Run', completed: true)record.bemi_changes.after_not(task: 'Walk')
# Query by the context valuesrecord.bemi_changes.context(user_id: 1)record.bemi_changes.context(user_id: 1, api_endpoint: '/tasks/complete')record.bemi_changes.context_not(user_id: 123)
# Chain methodsrecord.bemi_changes.before(task: 'Walk').after(task: 'Run')Filter by operation
Section titled “Filter by operation”record.bemi_changes.createdrecord.bemi_changes.updatedrecord.bemi_changes.deletedSort changes
Section titled “Sort changes”record.bemi_changes.ascrecord.bemi_changes.descBuild a custom query
Section titled “Build a custom query”changes = BemiChange. where(table: 'todos', operation: 'UPDATE'). where('context @> ?', { user_id: 1 }.to_json). order(committed_at: :desc). limit(10)Alternative gems
Section titled “Alternative gems”| Feature | PgStack | PaperTrail | Audited | Logidze |
|---|---|---|---|---|
| Change capture | CDC | Callbacks | Callbacks | Triggers |
| Open-source gem | ✅ | ✅ | ✅ | ✅ |
| Captures record deletions | ✅ | ✅ | ✅ | ❌ |
| Captures direct SQL changes | ✅ | ❌ | ❌ | ✅ |
| Independently scalable storage | ✅ Separate database | ❌ Versions table | ❌ Audits table | ❌ Row JSONB |
| No performance impact | ✅ Background CDC | ❌ Callback writes | ❌ Callback writes | ❌ Trigger writes |
| Easy-to-use UI | ✅ | ❌ | ❌ | ❌ |
For the broader tradeoffs between application libraries, triggers, and logical replication, see Alternatives.
License
Section titled “License”Distributed under the terms of the LGPL-3.0. If you need to modify and distribute the code, please release it to contribute back to the open-source community.
Copyright © 2026 PgStack
