hasandbelongstomany
Has_and_belongs_to_many, often abbreviated HABTM, is a data modeling pattern used to represent a direct many-to-many relationship between two models. In this approach, a join table links records from the two models, and the association is defined without an accompanying join model.
- Each model declares a HABTM association to the other. For example, a Book has_and_belongs_to_many :categories, and
- The join table contains two foreign keys, one for each model, and typically has no separate id
- Through the association, you can add or remove links between records using standard collection methods, such
Join table structure and conventions
- Columns: book_id and category_id (or the corresponding model name ids).
- Index: a composite unique index on the two foreign keys to prevent duplicate links.
- No join model by default; the join table is a pure linkage.
- HABTM is simple and convenient when no extra data needs to be stored on the relationship
- It does not support attributes on the association (such as a timestamp or role) without introducing
- For scenarios requiring extra attributes or validation on the association, has_many :through with an explicit join
- has_many :through with a join model allows richer metadata, validations, and callbacks on the association.
- Other frameworks may implement similar patterns with slight naming differences, but the core idea remains a
class Book < ApplicationRecord
has_and_belongs_to_many :categories
class Category < ApplicationRecord