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
class NotesController < ApplicationController
  def create
    @note = Note.new(note_params)
    if @note.save
      audit_log(@note, @note.account, "create")
      redirect_to note_path(@note), notice: t(:note_created)
    else
      render "new"
    end
  end

  def update
    if @note.update(note_params)
      audit_log(@note, @note.account, "update") if @note.saved_changes?
      redirect_to note_path(@note), notice: t(:note_updated)
    else
      render "edit"
    end
  end
end

This is an example controller where create and update events are being logged for the Note model.