Understanding Rails · Season 3: Active Record in depth
Callbacks: use and misuse
Episode 22 · deep dive · about 5 minutes · Rails 8.1 · by Tommy A. Caruso
How was this episode?
The series' author reads every note, and no one else sees it. When something is wrong or unclear, it gets fixed and the episode re-cut. How this series stays right.
Not endorsed yet. Are you a Rails developer? What's an endorsement?
Endorse this version To endorse: create an account, confirm your email, then link GitHub.
What changed
- Version 2, November 20, 2026: Rails keeps the counter cache when a note is saved or destroyed, not the database.
When a callback is right, and when it hides what your app does.
Free to watch. If it helped, support the series.
Transcript
0:00 Callbacks: use and misuse
Episode twenty two. Callbacks: use and misuse. A callback runs your code when a record is saved or destroyed, without anyone calling it by name. That's their power, and their danger. Today: when a callback is right, and when it hides what your app does.
0:20 The order they run in
Here's every save callback on the note model, each one printing its own name. Create a note, and they run in this order. Before validation, after validation. Before save, around save. Before create, around create, after create. Then after save. And last of all, after commit, once the transaction is done.
0:41 On update
Update the same note, and the create callbacks drop out. Validation, save and commit still run. There's a matching set for destroy, with before destroy and after destroy.
0:54 Inside the transaction
Everything up to after save runs inside one transaction. So if an after save callback raises, the insert is undone. Here, a pretend mail server is down. The error comes back, and there are still five hundred and two notes. A slow call to another service inside a callback holds that transaction open, too.
1:15 Methods that skip callbacks
Some methods run none of them. Update column printed nothing. Insert all printed nothing. Delete all doesn't run them either. These go straight to the database, so any rule that lives in a callback, they skip.
1:30 A counter that drifts
That has real effects. The counter cache from episode eighteen is kept by Rails when a note is saved or destroyed, not by the database. Create a note, and notes count goes up to five hundred. Delete it with delete all, and the count stays at five hundred, while the notebook really has four hundred and ninety nine notes. Reset counters puts it right.
1:52 When a callback is right
So when is a callback the right tool? When the work is about the record's own data. A tag's name should be cleaned up before the format rule checks it.
2:02 before_validation
Before validation, strip the name, lowercase it, and turn spaces into dashes. Big Ideas, with spaces around it, stays messy until it's validated. Then it's big dash ideas, and it passes. Rails has a declaration for exactly this job, normalizes, and it's in episode twenty three.
2:23 Only when something changed
A callback can also run only when something changed. Before save, if will save change to body. Update a note with the same body, and it stays quiet. Change the body, and body change shows the old text and the new one.
2:38 throw :abort
A before callback can also stop the action. Throw abort. Here, a note with replies refuses to be destroyed. Destroy returns false. Destroy with a bang raises record not destroyed. And the note is still there.
2:53 restrict_with_error
For that rule, Rails already has a built-in. Dependent, restrict with error, on the replies association. Destroy returns false, and the note gets an error: cannot delete record because dependent replies exist. Reach for the built-in first.
3:10 An email in a callback
Now the misuse. Say every new note should send an email. After create commit, deliver the note mailer later. It reads well, and it's one line.
3:21 Five hundred emails
Then someone imports five hundred notes from a script. Five hundred emails are queued. The same thing happens in the seed file, in the console, and in every test that creates a note. A callback can't tell a person writing a note from a script loading data.
3:38 In the controller instead
So put the email where a person creates a note: in the controller, right after a successful save. Post the form, and one email is queued. Import five hundred notes, and none are. Anyone reading the create action can see the email go.
3:54 A flag to skip it
And if you ever find yourself adding a flag just to skip a callback, like skip email, that's the code telling you the side effect lives in the wrong place.
4:04 after_commit
If a callback really must reach outside the database, use after commit. In this app, enqueue after transaction commit is false, so a job is sent the moment you ask. Send one from after create, and the job can start before the transaction commits, and not find the note. After commit waits until the note is really there.
4:26 Callbacks hide
The deeper problem is that callbacks hide. A save that sends an email, updates another model, and calls an outside service, all from inside the model, is a save nobody can predict. When a test fails, or a page is slow, the reason isn't in the code you're reading.
4:44 The rules
So here's a rule that holds up. Use callbacks for the record's own data: cleaning it up, filling in a field, keeping a count. Keep side effects out of them: emails, other models, jobs, outside services. Those belong where you can see them, in the controller, or in a method you call by name.
5:03 Next
Next: scopes, enums and normalizes.
Check your understanding
-
You create a note. Which of these callbacks runs last?
- after_save
- after_create
- after_commit
- around_save
Show answer
after_commit. after_commit runs once the transaction is done, after after_create and after_save. Source: Active Record Callbacks: creating an object (Rails Guides 8.1).
-
An after_save callback raises because the mail server is down. What happens to the note?
- It is saved, and the error is logged
- The insert is rolled back, and the error comes back to you
- It is saved, and save returns false
Show answer
The insert is rolled back, and the error comes back to you. The callback chain runs inside one transaction. If a callback raises, Rails rolls back and raises the error again. Source: Active Record Callbacks: halting execution (Rails Guides 8.1).
-
A note's belongs_to uses counter_cache: true. You remove a note with Note.where(id: note.id).delete_all. What happens to notes_count?
- It stays the same, so it is now wrong
- It goes down by one
- Rails raises, because delete_all can't be used with a counter cache
Show answer
It stays the same, so it is now wrong. Rails changes the count when a note is saved or destroyed. delete_all goes straight to the database and does neither. reset_counters puts the count right. Source: ActiveRecord::CounterCache (Rails source, v8.1.4.1).
-
In this app, enqueue_after_transaction_commit is false. Why send a job from after_commit instead of after_create?
- after_create does not run for new records
- Jobs can't be enqueued from a model
- after_commit runs before validation
- From after_create the job is queued right away and can start before the note is committed
Show answer
From after_create the job is queued right away and can start before the note is committed. With the setting false, the job is queued immediately. after_commit waits until the note is really in the database. Source: ActiveJob::Enqueuing (Rails source, v8.1.4.1).
Sources
Every example in this episode was run on Rails 8.1.4.1 and Ruby 4.0.2.