In an Active Record has_many, what do dependent: :destroy, :delete_all, :nullify and :restrict_with_error each do when the owner is destroyed?
answer
- default is do nothing
- destroy loads and calls callbacks
- delete_all is one SQL DELETE
- nullify sets the key to NULL
- restrict_with_error: base error, destroy false
basics
~20 sdependent: :destroy loads each child and destroys it with callbacks; :delete_all removes them in one SQL DELETE without callbacks; :nullify sets their foreign key to NULL; :restrict_with_error refuses, adding an error so destroy returns false. Without the option nothing happens.
solid answer
~40 s`dependent:` decides what happens to `board.cards` when the board is destroyed; without it Rails does nothing and leaves orphans. `:destroy` loads every card and calls `destroy` on each, so card callbacks and the cards' own dependents run. `:delete_all` issues one `DELETE ... WHERE board_id = ?` with no callbacks, so grandchildren are not touched. `:nullify` runs one `UPDATE` setting `board_id` to `NULL`, which needs a nullable column. `:restrict_with_exception` raises `ActiveRecord::DeleteRestrictionError` if cards exist, while `:restrict_with_error` adds a base error and makes `destroy` return `false`. `:destroy_async` hands the destroys to a background job. All of it is a `before_destroy` callback, so `board.delete` skips it.
code
ruby · 10 linesclass Board < ApplicationRecord
has_many :cards, dependent: :restrict_with_error
end
board = Board.find(7) # still has cards
board.destroy # => false
board.errors.full_messages # => ["Cannot delete record because dependent cards exist"]
board.cards.destroy_all # empty it first, with callbacks
board.destroy # => the destroyed boardgo deeper
Recall each value and whether it loads records and runs callbacks; know that leaving dependent: off leaves orphans.
Explain the SQL each value runs, why delete_all skips grandchildren, the callback-order trap and why board.delete bypasses the cascade.
Pick a strategy per association from callbacks, row counts and database constraints, and keep Rails cascades and database rules from contradicting each other.
Treat deletion policy as a data-lifecycle decision: what must survive, what must be audited, and which layer, Ruby or the database, owns each cascade.
## What dependent: decides In a kanban app, a `Board` has many `Card`s. When a board is destroyed, something has to happen to its cards, and the `dependent:` option on the association says what. Without it, Active Record does **nothing**: the cards stay in the table with a `board_id` that points at a deleted row (or, if the database has a foreign key constraint, the board's `DELETE` fails). ```ruby class Board < ApplicationRecord has_many :cards, dependent: :destroy end class Card < ApplicationRecord belongs_to :board has_many :comments, dependent: :destroy end ``` ## The values for has_many | Value | SQL it runs | Card callbacks | Typical use | |---|---|---|---| | none (default) | nothing | no | the children are managed elsewhere | | `:destroy` | loads every card, then one `DELETE` per card | yes, each card's own | children have callbacks or their own dependents | | `:delete_all` | one `DELETE FROM cards WHERE board_id = ?` | no | plain rows with nothing hanging off them | | `:nullify` | one `UPDATE cards SET board_id = NULL WHERE board_id = ?` | no | children should outlive the parent | | `:restrict_with_exception` | raises if any card exists | no | deleting a non-empty board is a bug | | `:restrict_with_error` | adds an error and aborts if any card exists | no | deleting a non-empty board is a user mistake | | `:destroy_async` | enqueues a background job after commit | yes, in the job | many children, slow callbacks | Details that interviewers probe: - **`:destroy`** runs every card's `destroy`, so `Card`'s own `dependent: :destroy` on comments cascades further down, and its callbacks fire. If any card refuses to be destroyed, `ActiveRecord::RecordNotDestroyed` is raised and the whole destroy rolls back. - **`:delete_all`** is a single statement and skips everything Ruby-side: no card callbacks, and the cards' comments are *not* deleted by Rails. They become orphans unless the database cascades them. - **`:nullify`** also clears the type column on a polymorphic association. It needs a nullable `board_id`, and `Card` should declare `belongs_to :board, optional: true`, or the orphaned cards can never be saved again. - **`:restrict_with_exception`** raises `ActiveRecord::DeleteRestrictionError` ("Cannot delete record because of dependent cards"). - **`:restrict_with_error`** adds a base error ("Cannot delete record because dependent cards exist") and makes `destroy` return `false`, which suits a controller that re-renders with a message. ## Other macros take a different list The accepted values depend on the macro, and a wrong one raises `ArgumentError` when the class loads: 1. `has_many`: `:destroy`, `:delete_all`, `:nullify`, `:restrict_with_error`, `:restrict_with_exception`, `:destroy_async`. 2. `has_one`: the same, but `:delete` instead of `:delete_all`, since there is one row. 3. `belongs_to`: only `:destroy`, `:delete` and `:destroy_async`. The API docs warn against it when the parent also has a `has_many` of these children, because destroying one child would remove a parent the other children still point at. `has_and_belongs_to_many` has no `dependent:` strategies to choose from: destroying the owner always deletes its join rows and never the associated records. ## It is a callback, so order and entry point matter `dependent:` on `has_many` and `has_one` is implemented as a `before_destroy` callback (on `belongs_to`, an `after_destroy`). Two consequences: - It runs only through `destroy`. `board.delete`, `Board.delete_all` and raw SQL skip callbacks, so the cards are left untouched. - Callbacks run in declaration order. A `before_destroy` declared *after* `has_many :cards, dependent: :destroy` sees the cards already gone; declare it first or pass `prepend: true`. ## Scoped associations only reach their scope `dependent:` acts on the rows the association can see. With `has_many :open_cards, -> { where(archived: false) }, class_name: "Card", dependent: :destroy`, destroying a board destroys only the open cards; archived cards keep a `board_id` pointing at a deleted board. Put the cascade on the unscoped association. ## Rails cascade or database cascade `dependent:` lives in Ruby; a foreign key with `ON DELETE CASCADE` or `ON DELETE SET NULL` lives in the database. They can overlap: with a database cascade in place, `dependent: :delete_all` is redundant, and `dependent: :destroy` still loads and destroys each card before the database would have. Decide which layer owns each cascade so they do not contradict each other. ## Choosing - Children with callbacks, attachments or their own dependents: `:destroy`, or `:destroy_async` when there are many. - Plain rows nothing else references: `:delete_all`. - History that must survive the parent: `:nullify`. - A parent that must be emptied first: one of the `restrict_with_` values, picking error versus exception by who made the mistake.
- Why does a before_destroy callback on Board sometimes find no cards to inspect?Because `dependent: :destroy` is itself a `before_destroy` callback and callbacks run in declaration order. If yours is declared after `has_many :cards, dependent: :destroy`, the cards are already destroyed. Declare it first or use `before_destroy :check_cards, prepend: true`.
- When should you choose :restrict_with_error over :restrict_with_exception?Use `:restrict_with_error` when a user can trigger the destroy and should see a message: `destroy` returns `false` and the board has a base error. Use `:restrict_with_exception` when a non-empty destroy means a programming error: it raises `ActiveRecord::DeleteRestrictionError`.
- On a has_many with a scope, what does dependent: :destroy destroy?Only the rows the scoped association returns. `has_many :open_cards, -> { where(archived: false) }, dependent: :destroy` leaves archived cards behind with a dangling `board_id`, so the cascade belongs on the unscoped `has_many :cards`.
- Without a dependent: option Rails deletes the children automatically.
- dependent: :delete_all runs each child's destroy callbacks.
- dependent: :delete_all also removes the children's own dependent rows.
- board.delete runs the dependent: cascade just like board.destroy.
- has_many accepts dependent: :delete for a single DELETE statement.
- restrict_with_error raises ActiveRecord::DeleteRestrictionError.