In an Active Record model, in what order do the lifecycle callbacks run when save is called on a new record?
answer
- validation callbacks come first
- save chain wraps the create chain
- around_save splits at yield
- after_save is still inside the transaction
- after_commit only after COMMIT
basics
~10 sSaving a new Active Record object runs before_validation, after_validation, before_save, around_save, before_create, around_create, the INSERT, after_create, after_save, then after_commit once the transaction commits. Updates swap each create hook for its update twin.
solid answer
~40 sValidation comes first: `before_validation`, the validators, `after_validation`. If the record is valid, the save chain opens with `before_save` and the code before `yield` in `around_save`, then the create chain runs: `before_create`, the first half of `around_create`, the `INSERT`, the rest of `around_create`, and `after_create`. The rest of `around_save` and then `after_save` close the save chain. All of that runs inside the transaction Rails opens for `save`; `after_commit` (or `after_rollback`) runs only when that transaction ends. For a persisted record the same sequence runs with `before_update`, `around_update` and `after_update` in place of the create callbacks. So tidy input in `before_validation`, derive columns in `before_save`, and leave anything the outside world sees for `after_commit`.
code
ruby · 19 linesclass GymMember < ApplicationRecord
before_validation { puts "1 before_validation" }
after_validation { puts "2 after_validation" }
before_save { puts "3 before_save" }
around_save :trace_save
before_create { puts "5 before_create" }
after_create { puts "6 after_create" }
after_save { puts "8 after_save" }
after_commit { puts "9 after_commit" }
private
def trace_save
puts "4 around_save before yield"
yield
puts "7 around_save after yield"
end
end
GymMember.create!(name: "Ana") # prints 1 to 9 in ordergo deeper
Recall the order: validation callbacks, then before_save, before_create, the INSERT, after_create, after_save, and after_commit last. Know that updates use the update callbacks instead.
Explain why validation runs before before_save, how around callbacks split at yield, and that everything up to after_save shares the save's transaction.
Use the order to place work: input cleanup before validation, derived columns before save, and external side effects only after commit, with conditions so no-op saves stay quiet.
Weigh how much behaviour a team lets the callback chain own; hidden order dependencies between callbacks are a maintenance cost that explicit service code avoids.
## What a callback is An Active Record **callback** is a method or block that Rails calls at a fixed point in a record's life cycle. You register it with a class macro such as `before_save :set_member_number` or `after_create_commit :send_welcome_sms`. Rails defines nineteen of them in `ActiveRecord::Callbacks`, and the order in which they fire is the first thing an interviewer checks, because it decides what each hook can safely do. ## The chain for a new record Calling `save` (or `create`) on a new `GymMember` runs, in this order: 1. `before_validation` 2. the validators themselves (`validates`, `validate`) 3. `after_validation` 4. `before_save` 5. `around_save`, up to its `yield` 6. `before_create` 7. `around_create`, up to its `yield` 8. the `INSERT` statement 9. the rest of `around_create`, then `after_create` 10. the rest of `around_save`, then `after_save` 11. `after_commit` or `after_rollback`, once the transaction ends Validation runs before any save callback, so a value set in `before_save` is never seen by the validators. If validation fails, `save` returns `false` and none of steps 4-10 run. ## Updates and destroys | Operation | Callbacks, in order | |---|---| | `save` on a new record | validation callbacks, `before_save`, `around_save`, `before_create`, `around_create`, `after_create`, `after_save`, `after_commit` | | `save` / `update` on a persisted record | validation callbacks, `before_save`, `around_save`, `before_update`, `around_update`, `after_update`, `after_save`, `after_commit` | | `destroy` | `before_destroy`, `around_destroy`, `after_destroy`, `after_commit` | The `_create` and `_update` chains are mutually exclusive: a given save runs one or the other, never both. `destroy` runs no validation callbacks at all. ## Around callbacks and the transaction boundary - An `around_*` callback must `yield`; the code before `yield` runs before the wrapped step and the code after it runs once that step and its own callbacks are done. - `save`, `save!` and `destroy` wrap the whole chain, `after_save` and `after_create` included, in one database transaction. Anything those hooks write rolls back if a later step raises. - `after_commit` and `after_rollback` are the only callbacks that run after the transaction has ended, which is why side effects that leave the database belong there. - Several `before_save` or `after_save` callbacks run in the order they are declared. ## Picking the hook - **`before_validation`**: clean user input the validators will check, such as stripping spaces from a phone number. - **`before_save`**: derive a column from other columns on every save, such as a full name. - **`before_create`**: set a value only new rows get, such as a membership number. - **`after_save` / `after_create`**: write related rows that must commit or roll back together with this one. - **`after_commit` variants**: talk to the outside world (SMS, search index, cache, jobs). ## What does not run the chain - `save(validate: false)` skips the validation callbacks but still runs the save and create or update callbacks. - `touch` skips validations and the save chain; it runs only `after_touch`, `after_commit` and `after_rollback`. - Methods that write SQL directly, such as `update_column`, `update_all` and `delete`, skip callbacks entirely; which write method to reach for is a separate topic. ## Three bugs the order explains 1. **A presence validation fails although a callback sets the value.** `validates :member_number, presence: true` together with `before_save :assign_member_number` rejects every new member, because validation runs before `before_save`. Assign the number in `before_validation on: :create`, or drop the validation and assign it in `before_create`. 2. **An SMS describes a member who never existed.** A text sent from `after_save` goes out before `COMMIT`; if anything later raises, the row rolls back but the message is already delivered. Commit callbacks exist for this. 3. **A save inside `after_save` loops.** Calling `save` on `self` from `after_save` re-enters the whole chain, including the same `after_save`. Set the value earlier, in a `before_*` callback, so a single write carries it. ## Inspecting a model's chain When an inherited model or a concern adds callbacks you did not write, list them instead of guessing. Each chain is exposed as `_<name>_callbacks`, so `GymMember._save_callbacks.map { |cb| [cb.kind, cb.filter] }` prints the save chain's kinds and filters. Callbacks declared in a parent class run before the child's, and a `prepend: true` option moves one to the front of its chain. Knowing the order lets you answer the follow-up interviewers like best: why a value set in `before_save` does not satisfy a presence validation, and why an SMS sent from `after_save` can describe a member who never existed.
- Does save on a persisted record with no changed attributes still run the update callbacks?Yes. With nothing changed Rails sends no `UPDATE`, but the save and update chains still run, so `before_save`, `after_update` and `after_save` fire, and `after_update_commit` fires when the transaction finishes. Guard side effects with a condition such as `if: :saved_change_to_phone?` when they should react only to real changes.
- How does before_validation on: :create differ from before_create?`before_validation on: :create` runs only when validation runs for a new record, so `save(validate: false)` skips it, and it runs even when validation then fails. `before_create` runs only after validation passed, right before the `INSERT`, and also runs with `validate: false`. Use the first to tidy input the validators check, the second for values that never come from the user.
- before_save runs before validation, so it can fix values the validators check
- after_save runs after COMMIT, so other connections already see the row
- after_create runs after after_save because creating is the last step
- Updating a record runs the create callbacks as well as the update ones
- save(validate: false) skips every callback, not only the validation ones