Understanding Rails

Understanding Rails · Season 3: Active Record in depth

Associations

Episode 18 · deep dive · about 6 minutes · Rails 8.1 · by

How was this episode?

The series' author reads every note, and no one else sees it. When something is wrong or unclear, it gets fixed and the episode re-cut. How this series stays right.

Was it clear?

Not endorsed yet. Are you a Rails developer? What's an endorsement?

Endorse this version To endorse: create an account, confirm your email, then link GitHub.

What changed

  • Version 2, November 20, 2026: Made clear that notes_count and notes.size read the counter cache, but notes.count still asks the database.

belongs_to, has_many, has_many through, has_one, and polymorphic.

Free to watch. If it helped, support the series.

Transcript

0:00 Associations

Episode eighteen. Associations. Real data is connected. A note lives in a notebook, a notebook holds notes, and a note carries tags. Associations are how Rails models those connections, and today we'll watch the SQL each one writes.

0:20 The models

Our app grows. A notebook holds notes. Tags label notes. A cover belongs to one notebook. And comments can be left on a note, or on a notebook.

0:31 references and foreign keys

Start in the database. Generate a migration, AddNotebookToNotes, notebook colon references. Rails writes add reference, notes, notebook, with null false, and foreign key true. That gives notes a notebook id column, an index on it, and a foreign key the database itself enforces.

0:50 belongs_to

In the Note model, one line: belongs to notebook. It's required by default. Try to save a note without one, and it fails: notebook must exist. Rails checks before the database ever sees it.

1:04 has_many

On the other side, Notebook has many notes. Now a notebook can make its own. Work dot notes dot create, and Rails fills in the notebook id for you.

1:15 The SQL they write

Every one of these is SQL you didn't have to write. Work dot notes dot count is select count, where the notebook id is one. Note dot notebook is a select from notebooks, by the note's notebook id.

1:28 Collection methods

Has many gives you a whole set of methods. Notes, notes dot build, notes dot create, notes dot where, and the shovel, to add one. Every one of them stays inside this notebook.

1:40 A scoped association

An association can carry its own query. Has many notes, with order, created at, descending, and every notebook's notes come newest first. The SQL gains an order by, and you never repeat it.

1:54 dependent

What happens to the notes when a notebook is destroyed? You decide, with dependent. Dependent destroy loads each note and destroys it, running its own callbacks, before the notebook goes.

2:06 What destroy deletes

Watch the order. Select the notes. Delete each note's taggings. Delete the note. Delete the cover. And last of all, the notebook.

2:16 The foreign key

Leave dependent off, and the foreign key protects you. Destroying a notebook that still has notes fails: foreign key constraint failed. The database refuses to leave notes pointing at nothing.

2:29 restrict_with_error

Or decide it in Rails. Dependent, restrict with error. Now destroy returns false, with an error you can show: cannot delete record, because dependent notes exist. There's also nullify, which empties the notebook id instead, when the column allows it.

2:47 counter_cache

Counting a notebook's notes runs a query every time. If you show that number often, keep it on the notebook instead. Add a notes count column, and belongs to notebook, counter cache true. Each new note now runs one small update: notes count, plus one. Reading notes underscore count, or notes dot size, asks the database nothing. Notes dot count still asks.

3:10 Many to many

Tags are different. A note can have many tags, and a tag can label many notes. That's many to many, and it needs a table in between: taggings, where each row holds a note id and a tag id.

3:23 has_many through

Tagging belongs to note, and to tag. Note has many taggings, and has many tags, through taggings. And Tag mirrors it.

3:32 The join

Now note dot tags, shovel, a new tag writes the tagging for you. And reading note dot tags is one query: select tags, inner join taggings on the tag id, where the note id is one.

3:45 has_and_belongs_to_many

In older apps you'll meet has and belongs to many: many to many, with no model in between. Has many through is the better default, because the join gets a model, and room to grow, like who added the tag, and when.

4:00 has_one

Has one is has many's singular cousin. A notebook has one cover. Its methods are singular too: notebook dot cover, and create cover, bang. Reading it adds limit one.

4:13 class_name and optional

Names don't have to match tables. A note can reply to another note. Belongs to parent, class name Note, optional true: optional, because most notes have no parent. And has many replies, class name Note, foreign key parent id. Now plan dot replies is a select from notes, where the parent id is the plan's.

4:34 Polymorphic

Now comments. A comment might belong to a note, or to a notebook. Instead of a column for each, a polymorphic association stores two things: an id, and the name of the model it belongs to.

4:47 commentable

Generate it with commentable, colon references, polymorphic. Comment belongs to commentable, polymorphic true. Note and Notebook each have many comments, as commentable. Leave a comment on a note, and Rails writes commentable type, Note, and commentable id, one.

5:05 The polymorphic trap

Here's the trade. A polymorphic reference has no foreign key, because one column can't point at two tables. Destroy the notebook, and its comments stay behind, pointing at nothing. Comment dot commentable returns nil. So add dependent destroy to each has many comments, because the database won't catch it for you.

5:27 The rules

So, the rules. Every belongs to gets a references migration, with a foreign key. Choose dependent on purpose, every time. Prefer has many through for many to many. And when you go polymorphic, clean up in Rails, because the database can't.

Next: querying, and the SQL behind where, order, joins, and includes.

Check your understanding

  1. Note has belongs_to :notebook with no other options. You save a new note that has no notebook. What happens?

    • The database raises a foreign key error
    • Rails saves it with a nil notebook_id
    • save returns false, with the error Notebook must exist
    Show answer

    save returns false, with the error Notebook must exist. belongs_to checks that the notebook is present by default, so Rails stops the save before the database sees it. Source: Active Record Associations: belongs_to (Rails Guides 8.1).

  2. Notebook has_many :notes, dependent: :restrict_with_error. You destroy a notebook that still has notes. What happens?

    • destroy returns false, and the notebook gets an error saying dependent notes exist
    • The notes are destroyed first, then the notebook
    • The notes keep the notebook, with notebook_id set to nil
    • Rails raises an exception
    Show answer

    destroy returns false, and the notebook gets an error saying dependent notes exist. restrict_with_error adds an error to the owner and leaves it in place. The exception is what restrict_with_exception does. Source: Active Record Associations: the :dependent option (Rails Guides 8.1).

  3. You add a notes_count column and belongs_to :notebook, counter_cache: true. What do you gain?

    • Notes are loaded with their notebook in one query
    • The count is kept on the notebook, so reading it asks the database nothing
    • Notes can no longer be created without a notebook
    Show answer

    The count is kept on the notebook, so reading it asks the database nothing. Rails keeps notes_count up to date as notes are added and removed, then reads the number from the notebook instead of running a COUNT. Source: Active Record Associations: counter_cache (Rails Guides 8.1).

  4. Comment belongs_to :commentable, polymorphic: true. Why can't the database stop a comment from pointing at a destroyed notebook?

    • SQLite does not support foreign keys
    • Rails skips foreign keys on any table with a type column
    • Foreign keys only work on has_many
    • A polymorphic reference can't have a foreign key, because one column can point at more than one table
    Show answer

    A polymorphic reference can't have a foreign key, because one column can point at more than one table. Rails refuses to add one: Cannot add a foreign key to a polymorphic relation. So add dependent: :destroy on each has_many :comments. Source: Table definitions and references in migrations (Rails source, v8.1.4.1).

Sources

Every example in this episode was run on Rails 8.1.4.1 and Ruby 4.0.2.

Comments

Sign in to comment or sign up.