In an Active Record model, what happens when a before callback calls throw :abort, and what do save, save!, destroy and destroy! return?
answer
- returning false no longer halts
- catch(:abort) in the before filter
- ActiveRecord::RecordNotSaved from save!
- ActiveRecord::RecordNotDestroyed from destroy!
- errors stay empty unless you add one
basics
~10 sCalling throw :abort in before_save, before_create, before_update or before_destroy cancels the later callbacks and the SQL, and the transaction rolls back. save and destroy return false; save! raises ActiveRecord::RecordNotSaved and destroy! raises ActiveRecord::RecordNotDestroyed.
solid answer
~40 sActive Support runs each `before_*` callback inside `catch(:abort)`; if it throws `:abort`, the chain is marked halted, the remaining callbacks and the `INSERT`, `UPDATE` or `DELETE` are skipped, the `after_*` callbacks do not run, and the transaction rolls back. `save` and `create` return `false`, `save!` raises `ActiveRecord::RecordNotSaved`, `destroy` returns `false` and `destroy!` raises `ActiveRecord::RecordNotDestroyed`. A halt in `before_validation` is different: `valid?` returns `false`, so `save!` raises `ActiveRecord::RecordInvalid`. Returning `false` from a callback halts nothing in current Rails; that form was deprecated in Rails 5.0. Rails also adds no error message for you, so call `errors.add` before throwing if a form has to explain the refusal.
code
ruby · 14 linesclass GymMember < ApplicationRecord
before_destroy :ensure_no_open_contract
private
def ensure_no_open_contract
return unless contract_ends_on&.future?
errors.add(:base, "Member has an open contract")
throw :abort
end
end
member.destroy # => false, member.errors[:base] holds the message
member.destroy! # raises ActiveRecord::RecordNotDestroyedgo deeper
Know that throw :abort, not returning false, stops a save or destroy, and that save and destroy then return false while the bang versions raise.
Explain the halting mechanism: the before filter catches :abort, later callbacks and the SQL are skipped, and the transaction rolls back; name RecordNotSaved and RecordNotDestroyed.
Spot the traps: guards ported from pre-5.0 code that return false, refusals that leave errors empty, and the before_validation halt that makes save! raise RecordInvalid.
Set a team convention for refusals, throw :abort plus an error for expected cases and exceptions for real failures, so callers can rely on return values.
## Halting with throw :abort Active Record callbacks are built on `ActiveSupport::Callbacks`. Its default **terminator** runs every `before_*` callback inside `catch(:abort)`. When a callback calls `throw :abort`, the chain is marked **halted**, and then: 1. every later `before_*` and `around_*` callback is skipped, 2. the SQL statement (`INSERT`, `UPDATE` or `DELETE`) never runs, 3. the `after_*` callbacks of that chain are skipped as well, 4. the transaction that `save` or `destroy` opened rolls back, and 5. the caller gets a failure value or an exception, depending on which method it called. ## What each call returns | Where `throw :abort` happens | `save` / `create` | `save!` / `create!` | `destroy` | `destroy!` | |---|---|---|---|---| | `before_validation` | `false` | `ActiveRecord::RecordInvalid` | n/a | n/a | | `before_save`, `before_create`, `before_update` | `false` | `ActiveRecord::RecordNotSaved` | n/a | n/a | | `before_destroy` | n/a | n/a | `false` | `ActiveRecord::RecordNotDestroyed` | The `before_validation` row surprises people. Halting there makes `valid?` return `false`, and `save!` treats an invalid record by raising `RecordInvalid`, even though the errors collection is empty. `update_attribute!`, added in Rails 7.1, raises `RecordNotSaved` when a `before_*` callback halts, where `update_attribute` just returns `false`. ## Why returning false is not enough Before Rails 5.0 a `before_*` callback that returned `false` halted the chain. Rails 5.0 deprecated that, and current Active Support only halts on `throw :abort`. A callback whose last expression happens to be `false` now does nothing special, which is a common bug in code ported from old apps: - `before_save { self.active = false }` used to cancel saves of inactive members by accident; today it simply saves. - `before_destroy { !contract_open? }` looks like a guard but halts nothing. ## Raising instead of throwing You can also stop a save by raising an exception from any callback. The transaction rolls back and the exception propagates out of `save` itself, so callers that expect `true` or `false` get an error instead. Rails does not re-raise two exception classes here, `ActiveRecord::Rollback` and `ActiveRecord::RecordInvalid`; `save` simply reports failure instead. Use `throw :abort` for an expected refusal and an exception for a genuine failure. ## Telling the user why A halt adds nothing to `errors`. If a controller re-renders a form after `destroy` returns `false`, the page shows no reason. Add one first: - `errors.add(:base, "Member has an open contract")` before `throw :abort`, - then let the controller read `member.errors.full_messages`. ## Around callbacks An `around_*` callback controls the wrapped step through `yield`. If it never yields, the step and the callbacks inside it do not run. Prefer `throw :abort` in a `before_*` callback for refusals; it is easier to read and returns predictable values. ## Where a guard belongs Not every refusal should be a callback. If the rule is about the data being valid, such as a start date before an end date, a validation is clearer: it fills `errors` automatically and `save!` raises the familiar `RecordInvalid`. Keep `throw :abort` for rules about whether an action may happen at all given the record's state, which validations do not express well: - refusing to destroy a member with an open contract, - refusing to update a record that has been archived, - refusing to create a duplicate booking that a database check would only reject later with a less helpful error. ## Debugging a silent refusal When `member.destroy` returns `false` and nobody knows why, work through it in order: 1. Call the bang version in a console: `destroy!` raises `ActiveRecord::RecordNotDestroyed`, which confirms a halt rather than a missing row. 2. Read `member.errors.full_messages`; a well-behaved guard explains itself there. 3. List the chain: `GymMember._destroy_callbacks.map(&:filter)` shows every `before_destroy`, including ones added by concerns or a parent class. 4. Look for guards that only throw under some condition and check that condition's data. ## Interview angle Interviewers use this question to separate people who have only read about callbacks from those who have debugged them. Expect follow-ups on why a destroy silently did nothing, why a form shows no error after a refused save, or why a guard ported from an old app stopped working.
- What does save! raise when a before_validation callback throws :abort?`ActiveRecord::RecordInvalid`, not `RecordNotSaved`. The halt makes `valid?` return `false`, and `save!` raises `RecordInvalid` for any invalid record, here with an empty errors collection. `RecordNotSaved` is what you get when the halt happens later, in `before_save`, `before_create` or `before_update`.
- When should a callback raise instead of throwing :abort?Throw `:abort` for an expected business refusal, such as deleting a member with an open contract, so `save` and `destroy` keep returning `false`. Raise when something is genuinely broken; the transaction still rolls back, but the exception reaches the caller of plain `save`, which is right for failures nobody should handle silently.
- Returning false from before_save cancels the save in current Rails
- throw :abort in before_destroy makes destroy raise RecordNotDestroyed
- A halted callback adds an error message to errors automatically
- after_save callbacks still run when before_save throws :abort
- throw :abort commits whatever was written before the halt