ruby
37 lines · 7 steps
Building an audit trail with Rails callbacks
An after_save callback records what changed on every Product write, filtering sensitive values along the way.
Explained by
highlit
1class Product < ApplicationRecord
2 belongs_to :account
3
4 after_save :record_audit_trail
5
6 private
7
8 def record_audit_trail
9 changes = saved_changes.except("created_at", "updated_at")
10 return if changes.empty?
11
12 action = saved_change_to_id? ? :create : :update
13
14 audit_logs.create!(
15 account: account,
16 actor: Current.user,
17 action: action,
18 changed_attributes: normalize(changes)
19 )
20 end
21
22 def normalize(changes)
23 changes.transform_values do |(from, to)|
24 { from: sanitize(from), to: sanitize(to) }
25 end
26 end
27
28 def sanitize(value)
29 return "[FILTERED]" if value.present? && self.class.filter_attributes.include?(value)
30
31 value
32 end
33
34 def audit_logs
35 AuditLog.where(auditable: self)
36 end
37end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Rails' dirty-tracking methods like saved_changes let you record exactly what a write changed without extra queries.
- 2Distinguishing create from update via saved_change_to_id? avoids passing an explicit flag through the callback.
- 3Sanitizing sensitive values before persisting keeps audit logs useful without leaking secrets.
Related explainers
ruby
class ProgressBar BAR_WIDTH = 40 def initialize(total, io: $stdout)
Building a terminal progress bar in Ruby
state tracking
terminal output
time estimation
Intermediate
8 steps
ruby
class Product < ApplicationRecord scope :search, ->(query) { return all if query.blank?
Building a multi-term search scope in Rails
arel
scopes
full-text search
Advanced
7 steps
ruby
module Rack class MaintenanceMode RETRY_AFTER = 3600
A Rack maintenance-mode middleware in Rails
middleware
rack
http-status
Intermediate
8 steps
java
public final class LogRedactor { private static final Pattern SECRET = Pattern.compile( "(?i)(password|token|api[_-]?key|secret|authorization)\\s*[=:]\\s*\\S+");
Streaming log redaction in Java
regex
streaming-io
try-with-resources
Intermediate
9 steps
ruby
class ImageNormalizer ORIENTATION_TRANSFORMS = { 1 => ->(img) {}, 2 => ->(img) { img.flop },
Correcting EXIF orientation in Ruby
lookup-table
lambdas
image-processing
Intermediate
7 steps
ruby
module RequestTagging class Middleware def initialize(app) @app = app
Per-request context with CurrentAttributes in Rails
middleware
thread-safety
logging
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-an-audit-trail-with-rails-callbacks-explained-ruby-636a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.