In an Active Record model, how do belongs_to, has_one and has_many differ, and which table holds the foreign key for each?
answer
- which side declares the key
- the child row points at the parent
- books.author_id, biographies.author_id
- single record or nil vs CollectionProxy
- build_author vs author.books.build
basics
~20 sbelongs_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.
solid answer
~30 sThe foreign key always lives on the table of the model that declares `belongs_to`. So `Book belongs_to :author` reads `books.author_id`, and `Author has_many :books` finds books whose `author_id` matches. `has_one :biography` is the same arrangement with one row: the key is `biographies.author_id`, and the reader returns a single record or `nil`. `has_many` returns a `CollectionProxy` that is empty, never `nil`. Each macro generates methods: `author`, `author=`, `build_author` and `create_author` for singular associations; `books`, `books<<`, `books.build`, `books.create` and `book_ids` for collections. None of them creates the column or a database constraint; the migration does that.
code
ruby · 10 linesauthor = Author.create!(name: "Ursula K. Le Guin")
book = author.books.create!(title: "The Dispossessed")
book.author_id # => author.id (key stored on books)
Author.new.books.to_a # => [] (empty collection, never nil)
author.biography # => nil until a biographies row points here
author.create_biography(body: "Short author bio")
author.biography.author_id # => author.id (key stored on biographies)go deeper
Recall the one rule: the foreign key lives on the table of the model that says belongs_to. Be ready to name the column for has_one and has_many.
Explain what each macro generates, why singular associations get build_x and create_x while collections get books.build, and what the readers return when nothing matches.
Argue key placement in a one-to-one from the data's dependency and creation order, and point out that the macros are Ruby only: integrity needs a migration-level constraint.
Frame association design as schema design first: the key's location fixes write order, nullability and which side can be created independently, so settle it before naming macros.
## The rule: the foreign key follows belongs_to Active Record has three everyday relation macros, and the first thing to settle is **where the foreign key column lives**. The rule is short: the model that declares `belongs_to` is the model whose table holds the key. `has_one` and `has_many` are declared on the *other* model, and they find rows in some other table whose key points back at them. In a used-bookstore catalogue: ```ruby class Author < ApplicationRecord has_many :books # finds books WHERE books.author_id = authors.id has_one :biography # finds the biography WHERE biographies.author_id = authors.id end class Book < ApplicationRecord belongs_to :author # reads books.author_id end class Biography < ApplicationRecord belongs_to :author # reads biographies.author_id end ``` The `authors` table holds no key at all. Both `books` and `biographies` carry an `author_id` column. ## The three macros side by side | Macro | Declared on | Key column lives in | Reader returns | |---|---|---|---| | `belongs_to :author` | `Book` | `books.author_id` | one `Author` or `nil` | | `has_one :biography` | `Author` | `biographies.author_id` | one `Biography` or `nil` | | `has_many :books` | `Author` | `books.author_id` | a `CollectionProxy`, never `nil` | `has_one` and `has_many` look the same from the database's point of view: both are "rows elsewhere point at me". The difference is cardinality in Ruby: `has_one` returns a single record (or `nil`), while `has_many` returns an association relation that is empty, not `nil`, when nothing matches. ## What each macro generates The macro is code generation. Each one adds methods to the model through a generated module: - **`belongs_to :author`** adds `author`, `author=`, `build_author`, `create_author`, `create_author!`, `reload_author`, plus `author_changed?` and `author_previously_changed?`. - **`has_one :biography`** adds `biography`, `biography=`, `build_biography`, `create_biography`, `create_biography!` and `reload_biography`. - **`has_many :books`** adds `books` (a `CollectionProxy` with `<<`, `build`, `create`, `create!`, `delete`, `destroy`, `size`, `exists?` and the rest), `books=`, `book_ids` and `book_ids=`. Singular associations get `build_x` / `create_x` because their reader returns the record itself, or `nil`, rather than a proxy, so there would be nothing to call `build` on when no row exists yet. Collections put `build` and `create` on the proxy instead: `author.books.build(title: "Dune")`. The `build` forms only instantiate an object with the key filled in; the `create` forms also save it. ## Naming conventions Rails infers Rails guesses everything from the association name, which is why the macros usually take no options: 1. The class: the association name, singularised first for collections, then camelised (`:author` gives `Author`, `:books` gives `Book`). 2. The key on `belongs_to`: the association name plus `_id` (`author_id`). 3. The key on `has_one` / `has_many`: the owner's class name, underscored, plus `_id` (`Author` gives `author_id` on the other table). 4. The primary key on the far side: `id`. When a name breaks the pattern, the `class_name:` and `foreign_key:` options override the guess; those options, and what they do to inverse detection, belong to the association-options topic. ## Choosing belongs_to or has_one Both sides of a one-to-one relation could in principle hold the key, so the choice is a schema decision: - Put the key on the row that **cannot exist without the other**. A biography makes no sense without its author, so `biographies.author_id` and `Biography belongs_to :author`. - Put the key where it lets the dependent row be created later. Authors are entered first; biographies arrive afterwards and reference them. - Don't flip it to "read nicely". `Author belongs_to :biography` would put `biography_id` on `authors`, which inverts the dependency and forces the biography to exist first. ## Mistakes interviewers listen for - Putting the key on the "owner" because the owner feels more important. Importance is irrelevant; the dependent row carries the key. - Expecting `author.books` to be `nil` and guarding with `if author.books`. A collection reader is always truthy; ask `author.books.any?` or `empty?` instead. - Declaring `has_one` where the data is really a list. If two biographies per author can ever exist (one per language, say), `has_one` will silently return just one of them. - Forgetting the other half. `belongs_to :author` alone works, but without `has_many :books` on `Author` you cannot write `author.books`. ## Things the macros do not do The macros are Ruby only. Declaring `belongs_to :author` does **not** add the `author_id` column or a database foreign key constraint; the migration does that. What `belongs_to` does add, by default in current Rails, is an application-level presence check that the author exists, which is a separate topic. And none of the three macros loads anything when it is declared: the query runs the first time the reader is called, and the result is cached on the owner object until `reload_author` or `author.books.reload`.
- In a one-to-one relation, how do you decide which model gets belongs_to?Put `belongs_to` on the model whose row cannot exist without the other, because that table gets the key column. A biography depends on its author, so `biographies.author_id` and `Biography belongs_to :author`, with `Author has_one :biography`. Flipping it would put `biography_id` on `authors` and force the biography to exist first.
- Does declaring belongs_to :author create the author_id column or a foreign key constraint?No. The macro only generates Ruby methods and, by default, an application-level check that the author exists. The `author_id` column, its index and any database foreign key constraint come from a migration. Without that constraint the database will accept an `author_id` that points at nothing.
- has_many :books puts a foreign key column on the authors table.
- belongs_to and has_one are interchangeable; pick whichever reads better.
- Declaring belongs_to :author adds the author_id column and a database constraint.
- author.books returns nil when the author has no books.
- A one-to-one has_one needs its own join table.