skip to content

In Active Record, when would you model a many-to-many link with has_many :through instead of has_and_belongs_to_many?

level: middleimportance: must knowfreq 70%

answer

  1. does the link carry its own data
  2. HABTM: no model, no primary key
  3. lexical join table: authors_books
  4. join model gets validations and callbacks
  5. through: :authorships, role column

basics

~20 s

Use has_many :through whenever the link itself needs attributes, validations, callbacks or its own queries, because it gives the join table a model. has_and_belongs_to_many suits only bare links with no model and no primary key, such as legacy join tables.

solid answer

~40 s

`has_and_belongs_to_many` links two models through a join table with no model class and no primary key, named from the two table names in lexical order (`books_tags`) unless you pass `join_table:`. It cannot expose extra columns, validate a link or run callbacks on it. `has_many :through` goes through a real model, such as `Authorship` with `belongs_to :author` and `belongs_to :book`, so the link can carry a `role`, validate uniqueness, have timestamps and be queried on its own. Because links tend to grow data, `has_many :through` is the default choice; HABTM fits a legacy table or a pure tag-style link you are sure will never need more.

code

ruby · 16 lines
ruby
class Book < ApplicationRecord
  has_and_belongs_to_many :tags           # table books_tags, no model

  has_many :authorships
  has_many :authors, through: :authorships
end

class Authorship < ApplicationRecord
  belongs_to :author
  belongs_to :book
  validates :author_id, uniqueness: { scope: :book_id }
end

book.authorships.create!(author: translator, role: "translator")
book.authors                       # authors via the authorships rows
Authorship.where(role: "translator").count

go deeper

for a junior

Recall the structural difference: HABTM has a bare join table with no model; has_many :through goes through a model you write.

for a middle

Explain what the join model enables (attributes, validations, callbacks, queries), how HABTM names its table, and why has_many :through is the default.

for a senior

Weigh migration cost: converting a live HABTM table to a join model needs a primary key and a model, so pick the join model early when the link may grow data.

for a principal

Treat the link as a domain concept: if the business talks about it (a contribution, a membership), it deserves a model and its own lifecycle rather than a hidden table.

## Two ways to say many-to-many Active Record offers two macros for a many-to-many relation, and interviewers ask when the **join model** wins. **`has_and_belongs_to_many`** (HABTM) links two models through a bare join table that has no model class and no primary key: ```ruby class Book < ApplicationRecord has_and_belongs_to_many :tags # expects table books_tags(book_id, tag_id) end class Tag < ApplicationRecord has_and_belongs_to_many :books end ``` **`has_many :through`** links them through a real model you write yourself: ```ruby class Authorship < ApplicationRecord belongs_to :author belongs_to :book validates :role, inclusion: { in: %w[author translator illustrator] } end class Book < ApplicationRecord has_many :authorships has_many :authors, through: :authorships end ``` ## How HABTM finds its table Without a `join_table:` option, HABTM derives the table name from the two table names in **lexical order**, joined by an underscore: `books` and `tags` give `books_tags`, `authors` and `books` give `authors_books`. The comparison is plain string ordering, so `paper_boxes` and `papers` give `paper_boxes_papers`, and a shared prefix appears once (`catalog_categories` and `catalog_products` give `catalog_categories_products`). The table holds the two key columns and nothing Rails will expose as attributes. Internally Rails builds HABTM as an anonymous join model plus a `has_many :through` over it. You never see that class, which is exactly the limitation: there is nowhere to put behaviour. ## What the join model buys you | Need | HABTM | has_many :through | |---|---|---| | Extra columns on the link (role, position, added_at) | not readable or writable as attributes | ordinary attributes | | Validations on the link (uniqueness of book plus author) | none | `validates` on the join model | | Callbacks when a link is created | none | `after_create` and friends | | Query the links directly | not as a model | `Authorship.where(role: "translator")` | | Timestamps on the link | no | `created_at`, `updated_at` | | Go through other associations | no | `through:` any association, nested | The used-bookstore catalogue shows the split. **Tags** on books are a pure link: a book is tagged "sci-fi" or it is not, and nothing else is recorded. HABTM is acceptable there. **Authorships** are not pure: a book has an author, a translator and an illustrator, ordered on the cover. The link has data, so it needs a model. ## The rule of thumb 1. If the relationship itself has attributes, rules or a lifecycle, use `has_many :through`. 2. If you are unsure, use `has_many :through`. Converting HABTM later means adding a primary key and a model to a live join table, while a join model that never grows costs one small class. 3. Use HABTM for a legacy schema that already has a bare join table, or for a link you are confident will never carry data. The API docs say the same thing in their own words: use `has_many :through` when you need to work with the relationship model as its own entity, and HABTM with legacy schemas or when you never work with the relationship directly. ## Behaviour that differs in practice - **Removing links.** `book.tags.delete(tag)` removes the join row in both styles; the `Tag` survives. On a `has_many :through`, that delete is a direct `DELETE` by default, so the join model's destroy callbacks do not run unless the through association says otherwise. - **Adding links.** `book.authors << author` on a persisted book saves a new `Authorship` immediately with `save!`, so an `Authorship` validation failure raises `ActiveRecord::RecordInvalid`. - **Destroying the owner.** Destroying a book with HABTM deletes its rows in `books_tags` automatically. With `has_many :through`, what happens to authorships depends on the options you put on `has_many :authorships`. - **Counting and ordering.** A join model can hold a `position` column and the through association can order by it (`has_many :authors, -> { order("authorships.position") }, through: :authorships`); HABTM has no model to give that column meaning. ## Reading it in an interview A good answer names the structural difference (no model and no primary key versus a full model), gives one concrete need that forces the join model (an attribute on the link), and states the default preference for `has_many :through`. A weak answer treats them as two spellings of the same thing, or believes HABTM is deprecated: it is not, it is simply narrower.

  • What table name does has_and_belongs_to_many :tags on Book expect, and how do you override it?
    It sorts the two table names lexically and joins them with an underscore, so `books` and `tags` give `books_tags`. Pass `join_table: "book_tag_links"` when the table is named differently, for example in a legacy schema.
  • Is has_and_belongs_to_many deprecated in Rails 8.1?
    No. It is still a supported macro, built internally as an anonymous join model plus a `has_many :through`. It is narrower, not retired: no attributes, validations or callbacks on the link, so most teams default to an explicit join model.
  • With has_many :authors, through: :authorships, what does book.authors.delete(author) remove?
    The `Authorship` row linking them, not the `Author`. Deletion on a through association is about the link. By default it is a direct `DELETE`, so `Authorship` destroy callbacks do not run unless the through association is configured to destroy.

HABTM is a sticky note pairing two names; has_many :through is a signed contract between them, with clauses, a date and a record you can file and look up later.

  • has_and_belongs_to_many is deprecated and removed in Rails 8.
  • A HABTM join table can expose extra columns like role as attributes.
  • HABTM join tables need an id primary key like any other table.
  • has_many :through and HABTM are two spellings of the same thing.
  • book.tags.delete(tag) deletes the Tag record itself.