Skip to the workspace
Pebellslearn by building
Models  ›  Lesson

Model Relationships (Associations)

Model Relationships 15 minbelongs_to sits on the model whose table holds the foreign key, has_many or has_one sits on the other side, and has_many :through connects two models via a join model.

ruby on rails / Model Relationships (Associations)

Explore each scene at your own pace.

01 · The rule

The rule

Model Relationships (Associations)

A review is always about a book, and a book collects many reviews. You could look them up by hand with Review.where(book_id: book.id), but Rails lets you declare the relationship once and then say book.reviews. Getting the declaration right comes down to one question: which table holds the foreign key?

The rule

The table with the foreign key belongs_to; the other side has_many.

class Review < ApplicationRecord
  belongs_to :book          # reviews.book_id
  belongs_to :member        # reviews.member_id
end

class Book < ApplicationRecord
  has_many :reviews, dependent: :destroy
end

class Member < ApplicationRecord
  has_many :reviews
  has_many :reviewed_books, through: :reviews, source: :book
end

What each gives you:

  • belongs_to :book — review.book, review.book = some_book. Since Rails 5 the book is required: a review without one fails validation. Add optional: true to allow none.
  • has_many :reviews — book.reviews, book.reviews.create(rating: 5, member: m), book.reviews.count.
  • has_one — like has_many but for a single record, such as has_one :profile.
  • has_many :through — reach across a join model. Members and books are many-to-many, and the reviews table sits between them.
  • dependent: :destroy — destroying the book destroys its reviews first, so none are left orphaned.

The foreign key column comes from the migration: book:references creates book_id. Rails guesses names from the association: belongs_to :book looks for book_id and the Book class.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.