Roll Your Own Audit Logging

Curated ago by @jeremysmithco

Description

Here’s a simple audit logging solution using an AuditLog ActiveRecord model with a polymorphic association, a Sidekiq worker, and an audit_log controller method. I wrote about the approach in Audit Logging in Rails.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class CreateAuditLogs < ActiveRecord::Migration[6.1]
  def up
    execute <<-SQL
      CREATE TYPE audit_log_event AS ENUM ('create', 'update', 'destroy');
    SQL

    create_table :audit_logs do |t|
      t.references :auditable, polymorphic: true, null: false, index: true
      t.references :account, null: false, foreign_key: true, index: true
      t.references :user, null: false, foreign_key: true, index: true
      t.column :event, :audit_log_event, default: "create", null: false
      t.datetime :created_at, null: false
    end
  end

  def down
    drop_table :audit_logs

    execute <<-SQL
      DROP TYPE audit_log_event;
    SQL
  end
end