Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Associations and Queries

Many-to-Many and Polymorphic Associations

Model many-to-many links with has_many :through and join models, understand has_and_belongs_to_many, and share one table across models with polymorphic associations, using runnable Ruby stand-ins.

Not every relationship is one-to-many. A student takes many courses and a course has many students. A post has many tags and a tag labels many posts. These are many-to-many relationships, and a database models them with a third table that holds one row per pair, called a join table. Rails gives you two ways to declare them, and one of them is almost always the better choice.

This lesson also covers polymorphic associations, where one table (comments, images, likes) can belong to many different kinds of parent. As in the previous lesson, belongs_to and has_many, real Rails code is read-only and the runnable blocks are plain-Ruby stand-ins.

has_many :through, the join model

With has_many :through, the join table gets its own model. It is a normal model that belongs_to both sides:

Ruby
class Student < ApplicationRecord
  has_many :enrollments, dependent: :destroy
  has_many :courses, through: :enrollments
end

class Course < ApplicationRecord
  has_many :enrollments, dependent: :destroy
  has_many :students, through: :enrollments
end

class Enrollment < ApplicationRecord
  belongs_to :student
  belongs_to :course
end

The migration for the join model:

Ruby
create_table :enrollments do |t|
  t.references :student, null: false, foreign_key: true
  t.references :course,  null: false, foreign_key: true
  t.string :grade
  t.timestamps
end
add_index :enrollments, [:student_id, :course_id], unique: true

Now student.courses runs one query with a JOIN, course.students does the reverse, and student.courses << course inserts an enrollment row. The big advantage is that the join model is a real object: it can carry extra data (grade, enrolled_on), validations, callbacks and its own scopes. The unique index prevents the same pair from being stored twice.

Ruby Stand-in: reading through a join model

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.

has_and_belongs_to_many

The older shortcut skips the join model entirely:

Ruby
class Post < ApplicationRecord
  has_and_belongs_to_many :tags
end

class Tag < ApplicationRecord
  has_and_belongs_to_many :posts
end

It needs a join table named after both tables in alphabetical order (posts_tags) with no id column and no extra columns:

Ruby
create_join_table :posts, :tags do |t|
  t.index [:post_id, :tag_id], unique: true
end

It is shorter, but you cannot add data, validations or callbacks to the link, and you cannot query the link itself. Many teams start with HABTM for tags and later wish they had a model. A good rule: use has_many :through unless you are very sure the link will never be anything but a pair of ids. Migrating from HABTM to through later means renaming tables and moving data.

Other through shapes

through also shortens chains of one-to-many links. A company has many departments, each has many employees:

Ruby
class Company < ApplicationRecord
  has_many :departments
  has_many :employees, through: :departments
end

company.employees joins across both tables. You can also use has_one :through for a single hop over another single association. These nested through associations are read-only in most cases because Rails would not know which intermediate row to create.

Polymorphic associations

Suppose both articles and photos can have comments. You could create article_comments and photo_comments, but a polymorphic association lets one comments table serve every model. It stores two columns: the id and the type (class name) of the parent.

Ruby
create_table :comments do |t|
  t.text :body
  t.references :commentable, polymorphic: true, null: false
  t.timestamps
end
# adds commentable_id (bigint) and commentable_type (string), plus a composite index
Ruby
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

class Article < ApplicationRecord
  has_many :comments, as: :commentable, dependent: :destroy
end

class Photo < ApplicationRecord
  has_many :comments, as: :commentable, dependent: :destroy
end

comment.commentable returns an Article or a Photo depending on the stored type. The as: :commentable option on the parent side tells Rails which name to use for the polymorphic pair.

Ruby Stand-in: a polymorphic belongs_to

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.

Both columns are needed in the key: id 1 exists in articles and in photos, so commentable_id alone is ambiguous. Polymorphism has a cost: the database cannot enforce a foreign key on commentable_id because it may point into any table. You trade referential integrity for flexibility. For a small, fixed set of parents, separate tables or an STI base class can be safer.

Never put user input into commentable_type. Rails instantiates the class named there (constantize), so a forged value could load an unexpected class. Always set the parent through the association (article.comments.create), not from raw params.

You query through the association by using the association names:

Ruby
Course.joins(:students).where(students: { name: "Ana" })
Student.includes(:courses).where(courses: { title: "Ruby" }).references(:courses)
Comment.where(commentable: article)       # works for polymorphic belongs_to

joins produces an INNER JOIN and does not load the other side. The next lessons, the query interface and eager loading, cover that in depth.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When should you prefer has_many :through over has_and_belongs_to_many?

    A join model is a real model, so it can hold data and behaviour. HABTM hides the join table.
  2. 2. A has_and_belongs_to_many join table between posts and tags should be named:

    Rails joins both table names in alphabetical order, so posts_tags. It has no id column.
  3. 3. Which two columns does t.references :commentable, polymorphic: true create?

    The id plus a string column that stores the parent's class name.
  4. 4. What is a downside of polymorphic associations?

    The id may point into any table, so no single foreign key constraint can apply.

Summary

  • Many-to-many links need a join table; has_many :through gives it a model.
  • Prefer through; HABTM is only for pure id pairs with no extra data.
  • Add a unique composite index on join tables.
  • Polymorphic associations share one table across parents using _id plus _type columns and as: on the parent side.
  • You give up database-level foreign keys with polymorphism, and must never take the type from user input.

Next: The query interface and scopes