skip to content

Dependent, Inverse & Counters

Association options decide what cascades and stays in sync: dependent: strategies, inverse_of, counter_cache, touch: and autosave:, plus deprecated associations. Interviewers ask why destroy is slow.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In an Active Record has_many, what do dependent: :destroy, :delete_all, :nullify and :restrict_with_error each do when the owner is destroyed?

level: juniorimportance: must knowfreq 72%

answer

  1. default is do nothing
  2. destroy loads and calls callbacks
  3. delete_all is one SQL DELETE
  4. nullify sets the key to NULL
  5. restrict_with_error: base error, destroy false

basics

~20 s

dependent: :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 lines
ruby
class 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 board

go deeper

for a junior

Recall each value and whether it loads records and runs callbacks; know that leaving dependent: off leaves orphans.

for a middle

Explain the SQL each value runs, why delete_all skips grandchildren, the callback-order trap and why board.delete bypasses the cascade.

for a senior

Pick a strategy per association from callbacks, row counts and database constraints, and keep Rails cascades and database rules from contradicting each other.

for a principal

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.
open as a page

In an Active Record belongs_to, what do counter_cache: true and touch: true keep in sync on the parent, and what bypasses them?

level: middleimportance: must knowfreq 60%

basics

~20 s

counter_cache: true keeps boards.cards_count up to date on card create, destroy and board change, so board.cards.size needs no COUNT query. touch: true sets the board's updated_at whenever a card changes. Both are callbacks, so delete_all, update_column and insert_all bypass them.

open as a page

In Active Record, what does inverse_of do, and when must you set it yourself alongside class_name:, foreign_key: or a scope?

level: middleimportance: should knowfreq 42%

basics

~20 s

inverse_of names the reverse association so Active Record links both ends in memory: card.board returns the same board object without a query. It is guessed automatically unless foreign_key:, through:, a scope on the inverse or non-matching names prevent it.

open as a page

In Active Record, what changes when you set autosave: true on a has_many, compared with leaving autosave unset or setting it to false?

level: seniorimportance: should knowfreq 33%

basics

~20 s

Unset, saving the parent saves only new children. autosave: true also saves changed loaded children, destroys ones marked with mark_for_destruction and copies their validation errors onto the parent, all in one transaction. autosave: false saves no children at all.

open as a page

In a Rails kanban app, why does destroying a board with thousands of cards through dependent: :destroy time out, and what are your options?

level: seniorimportance: should knowfreq 45%

basics

~20 s

dependent: :destroy loads every card and destroys each one, with its callbacks and cascades, inside the board's transaction. Use :delete_all for plain rows, :destroy_async to move per-card destroys into jobs enqueued after commit, a database cascade, or archive-then-purge.

open as a page

In Rails 8.1, how do you retire an Active Record association safely with deprecated: true, and what counts as using it?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

Rails 8.1 lets you mark has_many :swimlanes, deprecated: true. Every use, from generated methods and executed preloads to through associations and dependent: or touch: side effects, is then reported as a warning, exception or notification before you remove it.

open as a page