skip to content

Model Associations

Linking Active Record models: belongs_to, has_many and has_many :through, their dependent, inverse and counter options, STI, delegated types and nested attributes. Interviewers probe join models.

part ofRuby on Railsread it →
on this pageshow

explore

questions

21

In an Active Record Survey model, what does accepts_nested_attributes_for :questions add, and how does one save write the survey with its questions?

level: juniorimportance: must knowfreq 50%

answer

  1. generated questions_attributes= writer
  2. autosave switched on for the association
  3. array, or hash of hashes
  4. no id builds, matching id updates
  5. one transaction on the parent's save

basics

~10 s

accepts_nested_attributes_for :questions defines a questions_attributes= writer and turns on autosave, so nested hashes build or update questions in memory and one survey save writes everything in a single transaction.

solid answer

~40 s

On a `Survey` that `has_many :questions`, `accepts_nested_attributes_for :questions` generates `questions_attributes=` and sets autosave on the association. `Survey.create(title: "Onboarding", questions_attributes: [{ prompt: "Your role?" }, { prompt: "Team size?" }])` builds two unsaved questions in memory; the save then validates the survey and those questions, inserts the survey, and inserts each question with `survey_id` set, all inside the survey's transaction. A hash without `id` builds a new child; a hash with an `id` updates that child, and an id that is not one of this survey's questions raises `ActiveRecord::RecordNotFound`. Forms submit the collection as a hash keyed `"0"`, `"1"`, whose keys are ignored. `Question` can declare `accepts_nested_attributes_for :choices` too, so answer choices ride in the same payload.

code

ruby · 21 lines
ruby
class Survey < ApplicationRecord
  has_many :questions, dependent: :destroy
  accepts_nested_attributes_for :questions
end

class Question < ApplicationRecord
  belongs_to :survey
  has_many :choices, dependent: :destroy
  accepts_nested_attributes_for :choices
end

survey = Survey.create!(
  title: "Onboarding pulse",
  questions_attributes: {
    "0" => { prompt: "Your role?",
             choices_attributes: [{ label: "Engineer" }, { label: "Designer" }] },
    "1" => { prompt: "Team size?" }
  }
)
survey.questions.count                 # => 2
survey.questions.first.choices.count   # => 2

go deeper

for a junior

Recall the generated questions_attributes= writer, that hashes without id create children and hashes with id update them, and that one parent save writes it all.

for a middle

Explain that the macro turns on autosave, how the hash-of-hashes form shape is read, and why foreign ids raise RecordNotFound.

for a senior

Show you can run nested writes across three levels inside one transaction and know where they stop: no collection replacement, no updates on a new parent.

for a principal

Judge when nested attributes keep a form simple and when a dedicated form object or service is clearer for a multi-model write.

## What the macro defines **Nested attributes** let one model accept attributes for its associated records and save the whole graph through the parent. They are off by default; `accepts_nested_attributes_for` switches them on per association. In a survey builder, a `Survey` has many `Question` records and each question has many `Choice` records, and the goal is one form, one request and one save. Calling `accepts_nested_attributes_for :questions` on `Survey` does three things: - It defines a writer named after the association, `questions_attributes=`, so `questions_attributes` becomes an assignable key for `new`, `create`, `update` and `assign_attributes`. - It sets **autosave** on the `questions` association, which means the survey's validation and save also validate and save the questions held in memory. - It records the options (`allow_destroy:`, `reject_if:`, `limit:`, `update_only:`) that steer the writer. The macro looks the association up when it runs, so it must come after `has_many :questions`; otherwise it raises `ArgumentError` asking whether the association has been defined yet. It works for `has_many` and for one-to-one links (`has_one`, `belongs_to`), whose writer takes a single hash. ## The payload shapes | Shape | Example value for `questions_attributes` | How it is read | |---|---|---| | Array of hashes | `[{ prompt: "Role?" }, { id: 4, prompt: "Team?" }]` | each hash is one question | | Hash of hashes | `{ "0" => { prompt: "Role?" }, "1" => { prompt: "Team?" } }` | the keys are ignored, each value is one question | | One hash with an `id` key | `{ id: 4, prompt: "Team?" }` | treated as a single question | The hash-of-hashes shape is what an HTML form submits, because form fields have no natural way to express an array of hashes. Within each hash, `id` and `_destroy` are control keys that are never assigned as attributes. ## What a save does 1. **Assignment.** A hash without `id` builds a new question in `survey.questions`. A hash with an `id` finds that question among the survey's own questions and assigns the new values to it in memory; nothing is written yet. 2. **Validation.** Saving the survey validates it and, through autosave, the questions it is about to save. 3. **Writes.** The survey row is inserted or updated; then questions marked for destruction are destroyed, and each new or changed question is saved with `survey_id` pointing at the survey. 4. **Atomicity.** All of this happens inside the transaction the survey's save opened, so a failure anywhere leaves no partial survey behind. ## Where the writer is called from The generated writer is an ordinary attribute writer, so every mass-assignment entry point reaches it: - `Survey.new(attrs)` and `Survey.create(attrs)` build the questions while building the survey. - `survey.update(attrs)` assigns and saves inside one transaction, which also covers any side effects of the assignment. - `survey.assign_attributes(attrs)` only assigns; nothing is written until `save`. - Calling `survey.questions_attributes = [...]` directly is the same as any of the above for just that key. In a typical request, the controller hands the permitted survey parameters to one of these calls and then checks the boolean result of the save, exactly as it would for a model without children. ## Nesting a level deeper `Question` can declare `accepts_nested_attributes_for :choices` in turn. A single payload then carries a survey, its questions and each question's choices: `questions_attributes: [{ prompt: "Role?", choices_attributes: [{ label: "Engineer" }, { label: "Designer" }] }]`. Autosave cascades, so one `survey.save` writes rows in three tables. ## Traps - **Ids are scoped to the parent.** The writer looks ids up within this survey's questions, so an id belonging to another survey raises `ActiveRecord::RecordNotFound` with a message naming both models, rather than moving that question. - **Updating children while creating the parent fails.** A brand-new survey has no questions to match, so a hash with an `id` on `Survey.create` raises the same error. - **Only mentioned children change.** Questions not listed in the payload are left as they are; nested attributes do not replace the collection. - **The writer is only half the feature.** The form side and the controller's permitted keys for `questions_attributes`, including `id` and `_destroy`, are configured elsewhere and must match what the model accepts.

  • What happens if questions_attributes contains an id that belongs to another survey?
    The writer looks ids up only among this survey's questions, so it raises `ActiveRecord::RecordNotFound` with a message naming the question id and the survey. It never fetches the foreign question and re-parents it.
  • Why must accepts_nested_attributes_for come after has_many :questions in the class body?
    The macro reads the association's reflection when it runs, to switch on autosave and pick a collection or one-to-one writer. If `has_many :questions` is not declared yet, it raises `ArgumentError` asking whether the association has been defined.
  • How is the hash of hashes from a form different from an array of hashes?
    Only in shape. The writer takes the values of a hash of hashes and ignores keys such as `"0"` and `"1"`, unless the hash itself has an `id` key, in which case it is treated as one record. Both shapes produce the same questions.

  • Assigning questions_attributes inserts each new question row immediately.
  • The survey and its questions save in separate transactions, so a failing question leaves the survey behind.
  • A hash without an id updates the first existing question.
  • Keys like "0" and "1" in questions_attributes become the questions' ids.
  • accepts_nested_attributes_for :questions can be declared before has_many :questions.
open as a page

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%

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.

open as a page

In an Active Record model, how do belongs_to, has_one and has_many differ, and which table holds the foreign key for each?

level: juniorimportance: must knowfreq 80%

basics

~20 s

belongs_to sits on the model whose table holds the foreign key (books.author_id). has_one and has_many sit on the other model and find rows pointing back at it: has_one returns one record or nil, has_many an association collection.

open as a page

In Active Record single-table inheritance, what does the type column store, and how does it shape queries and loaded objects?

level: middleimportance: must knowfreq 48%

basics

~20 s

Active Record STI keeps every subclass in the parent's table and writes the class name into the type column. Subclass queries add a type filter, and each loaded row is instantiated as the class its type names.

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, when would you model a many-to-many link with has_many :through instead of has_and_belongs_to_many?

level: middleimportance: must knowfreq 70%

basics

~20 s

Use has_many :through whenever the link itself needs attributes, validations, callbacks or its own queries, because it gives the join table a model. has_and_belongs_to_many suits only bare links with no model and no primary key, such as legacy join tables.

open as a page

In an Active Record Employee model, how do you declare a self-referential manager link and the reports that point back to it?

level: juniorimportance: should knowfreq 40%

basics

~10 s

Add a manager_id column to employees, then declare belongs_to :manager, class_name: "Employee", optional: true and has_many :reports, class_name: "Employee", foreign_key: :manager_id, inverse_of: :manager.

open as a page

In Rails 8.1, why does saving a Book that belongs_to :author fail with "Author must exist", and how do you allow authorless books?

level: juniorimportance: should knowfreq 62%

basics

~20 s

belongs_to is required by default: Rails adds a presence validation on the association whose message is "must exist". Declare belongs_to :author, optional: true to allow a nil author, and make the author_id column nullable to match.

open as a page

In Active Record, what does self.abstract_class = true change for a shared parent model compared with an STI base class?

level: middleimportance: should knowfreq 33%

basics

~20 s

self.abstract_class = true takes the parent out of the table mapping: it has no table, cannot be instantiated, and each subclass gets its own table. An STI base owns one shared table that its subclasses write into with a type column.

open as a page

In Rails nested attributes, how do the id and _destroy keys decide whether a child record is created, updated or deleted?

level: middleimportance: should knowfreq 42%

basics

~20 s

A hash without id builds a child and one with an id updates that child. With allow_destroy: true, a truthy _destroy marks it for deletion on the parent's save; without it, _destroy is ignored. Children left out are untouched.

open as a page

In Rails, what do accepts_nested_attributes_for's reject_if: :all_blank and limit: options do to an incoming questions_attributes payload?

level: middleimportance: should knowfreq 32%

basics

~20 s

reject_if: :all_blank silently skips any child hash whose values are all blank, not counting _destroy, and a proc or method name can apply any rule. limit: caps how many hashes the writer accepts and raises NestedAttributes::TooManyRecords above it.

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, how does belongs_to with polymorphic: true pair with as: on the other models, and what does it cost you?

level: middleimportance: should knowfreq 52%

basics

~10 s

belongs_to :taggable, polymorphic: true stores taggable_id and taggable_type (the target's class name), and each target declares has_many :taggings, as: :taggable. The cost: no database foreign key, class names in your data, and no build_taggable.

open as a page

In a Rails fleet app modelling vans, trucks and e-bikes, when does STI become sparse and brittle, and what does delegated_type change?

level: seniorimportance: should knowfreq 30%

basics

~20 s

STI turns sparse and brittle once subtypes carry many columns of their own: those columns sit NULL on every other row and cannot be NOT NULL. delegated_type keeps shared columns on vehicles and moves each subtype's columns to its own table.

open as a page

When a Rails survey saved with nested questions fails validation, how do the child errors reach the survey, and what gets written?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Nested attributes turn on autosave, so validating the survey also validates its new and changed questions and copies their errors onto the survey as keys like questions.prompt. The save returns false and nothing is written.

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 an Active Record model, why can assigning book.tag_ids or calling book.tags << tag change the database before book.save fails, and how do you keep it atomic?

level: seniorimportance: should knowfreq 32%

basics

~20 s

On a persisted owner, collection writers such as tag_ids=, tags= and << write immediately in their own transaction, so a later failed save cannot undo them. Use update, which wraps assignment and save in one transaction, or an explicit transaction with save!.

open as a page

In Active Record STI, what do becomes and becomes! do, and which one changes what is saved to the type column?

level: middleimportance: nice to knowfreq 20%

basics

~20 s

becomes(klass) returns an instance of another class sharing the record's attributes, leaving the type column alone, which suits rendering or routing as the parent. becomes!(klass) also writes the new class into the type column, so saving reclassifies the row.

open as a page

In Rails nested attributes on a has_one, what happens to the existing record when the attributes lack an id, and what does update_only: true change?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

Without an id, a has_one's nested writer builds a replacement and immediately detaches or destroys the existing record according to the association's dependent option. update_only: true makes the writer update the existing record in place, id or not.

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