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
class AuditLogWorker
  include Sidekiq::Worker

  def perform(auditable_gid, account_id, user_id, event)
    auditable = parse_global_id(auditable_gid)
    account = Account.find_by(id: account_id)
    user = User.find_by(id: user_id)

    AuditLog.create!(auditable_type: auditable.model_name, auditable_id: auditable.model_id, account: account, user: user, event: event)
  end

  private

  # Use GlobalID.parse instead of GlobalID::Locator.locate because the record
  # may be destroyed and we don't want to raise ActiveRecord::RecordNotFound
  def parse_global_id(gid)
    GlobalID.parse(gid)
  end
end

This worker uses Rails Global ID for the polymorphic auditable ID.