Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Associations and Queries

Associations - belongs_to and has_many

Learn how Rails models relate to each other with belongs_to, has_many and has_one, foreign keys, dependent options and inverse_of, with runnable Ruby stand-ins that show how the readers work.

Real applications are made of things that point at other things. A comment belongs to a post. A post has many comments. A user has one profile. In a database those links are foreign keys: a comments table has a post_id column holding the id of the post it belongs to. Active Record turns that column into Ruby methods, so you write post.comments and comment.post instead of joining tables by hand.

This lesson covers the three one-line declarations that do most of the work: belongs_to, has_many and has_one. Rails itself cannot run on this page (the runner has no gems and no database), so the real model code is shown read-only and the runnable examples are small Ruby stand-ins that mimic what the declarations do. If you want the table side first, see SQL joins.

The foreign key lives on the "belongs to" side

Suppose you generate two models:

SH
bin/rails generate model Post title:string body:text
bin/rails generate model Comment post:references body:text

The post:references part adds a post_id column plus an index and a database foreign key to the migration. Then the models declare the relationship from both ends:

Ruby
class Post < ApplicationRecord
  has_many :comments, dependent: :destroy
end

class Comment < ApplicationRecord
  belongs_to :post
end

Rule of thumb: the model whose table holds the _id column gets belongs_to. The other side gets has_many or has_one. Mixing this up is the most common beginner mistake, and the error message (unknown attribute 'post_id') is the clue.

Since Rails 5, belongs_to is required by default: saving a comment without a post fails validation with "Post must exist". Write belongs_to :post, optional: true when the link may be empty.

What the declarations give you

has_many :comments adds post.comments (a lazy relation), post.comments.build, post.comments.create, post.comment_ids, post.comments << comment and more. belongs_to :post adds comment.post and comment.post=. has_one :profile adds user.profile and user.build_profile.

Underneath, these are ordinary reader methods that look up rows by foreign key. This stand-in implements the idea with arrays:

Ruby Stand-in: a has_many reader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice that has_many filters the child table by post_id, and belongs_to finds one parent by id. Active Record does exactly this with SQL: SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1.

Reading, building and creating through the association

Going through the association sets the foreign key for you:

Ruby
post = Post.find(1)
post.comments.create(body: "Saved immediately")   # INSERT now
c = post.comments.build(body: "Not saved yet")    # in memory only
c.save                                            # INSERT now
post.comments.count      # runs SELECT COUNT(*)
post.comments.size       # uses the loaded array if loaded, else COUNT
post.comments.any?       # cheap EXISTS-style check

Prefer size when the records may already be loaded, count when you always want a fresh count, and exists? or any? for yes/no questions. Never call length on a huge unloaded relation: it loads every row.

has_one: a single partner

has_one is has_many limited to one row, and the foreign key still lives on the other table.

Ruby
class User < ApplicationRecord
  has_one :profile, dependent: :destroy
end

class Profile < ApplicationRecord
  belongs_to :user
end

user.profile returns the profile or nil. user.build_profile(bio: "...") makes a new one. Assigning a new profile with user.profile = other removes the link to the old one (and, with dependent: :destroy, deletes it).

dependent: what happens to the children

When you delete a post, what should happen to its comments? Without a rule, the database may refuse (foreign key constraint) or leave orphans. The dependent: option decides:

Option Effect when the parent is destroyed
:destroy loads each child and calls destroy (runs callbacks)
:delete_all one DELETE statement, no callbacks
:nullify sets the foreign key to NULL
:restrict_with_error refuses and adds an error to the parent
:restrict_with_exception raises ActiveRecord::DeleteRestrictionError

Choose :destroy when children have their own cleanup (callbacks, attached files). Choose :delete_all for large piles of simple rows.

Ruby Stand-in: dependent options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

inverse_of and class_name

Rails guesses the other side of a link from the names, so has_many :comments finds Comment, and belongs_to :post finds Post. With standard names, Rails also detects the inverse automatically, which means post.comments.first.post reuses the same in-memory post instead of querying again. When the names are not standard you tell Rails:

Ruby
class Post < ApplicationRecord
  belongs_to :author, class_name: "User", foreign_key: :author_id, inverse_of: :posts
end

class User < ApplicationRecord
  has_many :posts, foreign_key: :author_id, inverse_of: :author
end

class_name names the model, foreign_key names the column, and inverse_of names the matching association on the other side.

Add a database index on every foreign key (references does this) and a real foreign key constraint (foreign_key: true). Rails validations can be bypassed by update_column or raw SQL, but a database constraint cannot.

Counter caches

Counting children on every page is wasteful. A counter cache stores the count on the parent:

Ruby
class Comment < ApplicationRecord
  belongs_to :post, counter_cache: true   # needs comments_count on posts
end

Now post.comments.size reads the integer column comments_count without a query, and Rails keeps it correct when comments are created or destroyed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which table holds the foreign key in a Post has_many Comments relationship?

    The child table (comments) holds post_id, and the child model declares belongs_to :post.
  2. 2. What does belongs_to require by default since Rails 5?

    Without optional: true, saving a record with no parent fails with the validation error 'must exist'.
  3. 3. Which dependent option deletes children with a single SQL statement and runs no callbacks?

    :delete_all issues one DELETE and skips callbacks, unlike :destroy which loads and destroys each child.
  4. 4. Why add counter_cache: true to belongs_to?

    The parent gets a comments_count column that Rails keeps in sync.

Summary

  • The _id column lives on the table of the model that declares belongs_to.
  • has_many and has_one add readers, builders and creators that set the foreign key for you.
  • belongs_to is required unless you write optional: true.
  • dependent: decides what happens to children when a parent is destroyed.
  • Use class_name, foreign_key and inverse_of for non-standard names.
  • Index foreign keys and consider counter caches for hot counts.

Next: Many-to-many and polymorphic associations