ruby 48 lines · 8 steps

Per-request audit trails with Current in Rails

How CurrentAttributes carries request context so models can stamp who changed what, and when.

Explained by highlit
1class Current < ActiveSupport::CurrentAttributes
2 attribute :user, :request_id, :user_agent, :ip_address
3 
4 resets { Time.zone = nil }
5 
6 def user=(user)
7 super
8 Time.zone = user&.time_zone
9 end
10end
11 
12class ApplicationController < ActionController::Base
13 before_action :set_current_request_details
14 
15 private
16 
17 def set_current_request_details
18 Current.request_id = request.uuid
19 Current.user_agent = request.user_agent
20 Current.ip_address = request.remote_ip
21 Current.user = current_user
22 end
23end
24 
25module Auditable
26 extend ActiveSupport::Concern
27 
28 included do
29 belongs_to :created_by, class_name: "User", optional: true
30 belongs_to :updated_by, class_name: "User", optional: true
31 
32 before_create { self.created_by ||= Current.user }
33 before_save { self.updated_by = Current.user if changed? }
34 
35 has_many :versions, as: :item, class_name: "AuditVersion", dependent: :destroy
36 after_update :record_version
37 end
38 
39 private
40 
41 def record_version
42 versions.create!(
43 whodunnit: Current.user&.id,
44 request_id: Current.request_id,
45 changeset: saved_changes.except("updated_at", "updated_by_id")
46 )
47 end
48end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1CurrentAttributes gives you request-scoped globals that reset automatically between requests, avoiding leaked state across threads.
  2. 2Concerns let you attach associations and callbacks to any model, centralizing cross-cutting behavior like auditing.
  3. 3Threading request context through Current keeps models decoupled from the controller yet aware of who triggered a change.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Per-request audit trails with Current in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code