ActiveRecord callbacks
This course covers the order in which Rails runs ActiveRecord callbacks around save, create, update and destroy. Each stage is traced on a scratch table, from before_validation to after_save. It shows how around_save and around_create wrap the database write with a yield. It explains why Identity::User normalizes email in before_save and builds its default preference row in after_create. It also covers throw :abort, which halts a save or destroy while leaving errors empty, and when logic belongs in a service object instead.
What you'll learn
- ✓The fixed order of callback stages on create, update and destroy
- ✓When to use before_save versus after_create, and why the id matters
- ✓Getting a once-only effect with a conditional before_validation
- ✓How around_save and around_create wrap the write with yield
- ✓How throw :abort halts a save or destroy and how it differs from a validation
- ✓Where a callback ends and a service object should take over
The callback lifecycle, in order
ActiveRecord validations (complex) ended on one question: is this record allowed to be saved? What happens before, during and after the save itself was left for this course. So this course opens with a direct question: when .save runs, in what order does Rails do everything around it?
Read the full lesson free →Curriculum
7 lessonsThe callback lifecycle, in order
Traces the full callback order on create, update and destroy using a scratch table that logs each stage.
before_save vs. after_create in this app
Explains why Identity::User normalizes email in before_save and creates its preference row in after_create.
create vs. update: callbacks that only fire once
Compares create and update callbacks with a conditional before_validation that fills a value only while blank.
around_save and around_create: wrapping both sides
Shows how around_save and around_create split code around yield and nest inside each other.
throw :abort halts the chain
Shows how throw :abort halts a save or destroy, returns false and leaves errors empty.
Callbacks vs. service objects: a design tension
Examines the hidden callback effects of a service's save call and where business logic belongs in this project.
Putting it together: the full save lifecycle
Reviews the full save lifecycle, the two Identity::User hooks, throw :abort and the callback and service boundary.