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
class AuditLog < ApplicationRecord
  belongs_to :auditable, polymorphic: true, optional: true
  belongs_to :account
  belongs_to :user

  enum event: { created: "create", updated: "update", destroyed: "destroy" }, _suffix: true
end

Auditable is optional because it may be destroyed when record is created. The event enum contains any event actions we’re tracking.