Goal

You’ll be able to set up has_many and belongs_to associations correctly, and understand precisely which side of the relationship needs the foreign key column — a detail that genuinely trips up many beginners.

Learn

Associations let Rails models represent real relationships between database tables:

class Author < ApplicationRecord
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :author
end

This lets you navigate the relationship naturally in both directions:

author.books           # all books belonging to this author
book.author            # the author this book belongs to
author.books.create(title: "New Book")  # create a book already associated with this author

Here’s the genuinely important detail: belongs_to is the side that needs the actual foreign key column in its database table. In this example, the books table needs an author_id column — Book “belongs to” an Author, so Book holds the reference. The authors table needs no corresponding column at all; has_many is inferred purely by Rails looking for that foreign key on the other table.

class CreateBooks < ActiveRecord::Migration[7.0]
  def change
    create_table :books do |t|
      t.string :title
      t.references :author  # this adds the author_id column
      t.timestamps
    end
  end
end

t.references :author is the standard way to add this foreign key column in a migration, and it automatically sets up the correct index too, which matters genuinely for query performance as the table grows.

Decision Task

You’re setting up a relationship where a Comment belongs to a Post. Before reading on: which table needs the actual foreign key column — comments or posts?

Show Answer

comments — since Comment uses belongs_to :post, the comments table needs a post_id column, following the rule that belongs_to is always the side holding the actual foreign key. The posts table needs no corresponding column at all; Post’s has_many :comments is inferred by Rails looking for that post_id column on the comments table.

Common Mistake

Adding the foreign key column to the wrong table — for example, adding author_id to the authors table instead of the books table for a has_many/belongs_to relationship. The foreign key always belongs on the belongs_to side (the “many” side pointing back to the “one”), not the has_many side; getting this backwards causes the association to simply not work correctly.

Practice Questions

1. Set up a has_many/belongs_to association between a Team (has many players) and a Player (belongs to one team).

Show Answer

class Team < ApplicationRecord\n has_many :players\nend\n\nclass Player < ApplicationRecord\n belongs_to :team\nend

2. Given the Team/Player association above, which table needs the foreign key column, and what would it be called?

Show Answer

The players table needs the foreign key, called team_id, since Player uses belongs_to :team.

3. Write the migration line that adds the correct foreign key column for a Player belonging to a Team.

Show Answer

t.references :team (inside the players table’s migration)

4. True or False: has_many requires its own table to have a foreign key column pointing back to the model with belongs_to.

Show Answer

False — the has_many side needs no column at all; the foreign key lives specifically on the belongs_to side’s table.

5. Given team.players, what does this actually return?

Show Answer

All Player records associated with that specific team, found via the team_id foreign key on the players table.

Try It Yourself

Without looking back, set up a has_many/belongs_to association between a Customer (has many orders) and an Order (belongs to one customer), including the correct migration line for the foreign key.

Show Answer

class Customer < ApplicationRecord\n has_many :orders\nend\n\nclass Order < ApplicationRecord\n belongs_to :customer\nend — with t.references :customer in the orders table’s migration, since orders (the belongs_to side) needs the foreign key.

Quick Check

1. What does has_many :books on an Author model let you do?

Show Answer

Access all books belonging to that author via author.books.

2. What does belongs_to :author on a Book model require in the database?

Show Answer

An author_id foreign key column on the books table.

3. Which side of a has_many/belongs_to relationship holds the actual foreign key?

Show Answer

The belongs_to side.

4. What migration method adds a correctly-named foreign key column with an index?

Show Answer

t.references :model_name

5. If Comment belongs_to :post, what foreign key column does the comments table need?

Show Answer

post_id

تحميل هذا الباب / Download this Chapterنسخة كاملة للدراسة بدون إنترنت، مع الأسئلة والإجابات والصور المتاحة.