How to Use has_many in Rails: Simple Association Guide
In Rails, use
has_many in a model to declare a one-to-many relationship with another model. This tells Rails that one record of this model can be linked to many records of the other model, enabling easy data access and management.Syntax
The has_many method is used inside a Rails model to set up a one-to-many connection. It takes the name of the related model in plural form as a symbol. You can add options like dependent to control what happens to related records when the parent is deleted.
- has_many :items - declares the association
- dependent: :destroy - deletes associated records when the parent is deleted
ruby
class Author < ApplicationRecord
has_many :books, dependent: :destroy
endExample
This example shows an Author model that has_many Book models. You can create an author and add many books to it. Rails lets you easily access all books of an author with author.books.
ruby
class Author < ApplicationRecord has_many :books, dependent: :destroy end class Book < ApplicationRecord belongs_to :author end # Usage in Rails console or controller author = Author.create(name: "Jane Doe") author.books.create(title: "Book One") author.books.create(title: "Book Two") puts author.books.pluck(:title).join(", ")
Output
Book One, Book Two
Common Pitfalls
Common mistakes include forgetting to add the matching belongs_to in the related model, which breaks the association. Another is not setting dependent: :destroy when you want related records removed automatically, causing orphan records. Also, using singular instead of plural in has_many will cause errors.
ruby
class Author < ApplicationRecord # Wrong: singular instead of plural has_many :book end # Correct usage: class Author < ApplicationRecord has_many :books, dependent: :destroy end
Quick Reference
| Option | Description |
|---|---|
| has_many :association_name | Declares one-to-many relationship |
| dependent: :destroy | Deletes associated records when parent is deleted |
| class_name: 'ModelName' | Use if association name differs from model name |
| foreign_key: 'key_name' | Specify custom foreign key |
| through: :other_association | Set up many-to-many through another model |
Key Takeaways
Use has_many in the parent model to declare one-to-many relationships.
Always add belongs_to in the child model for the association to work.
Use dependent: :destroy to clean up associated records automatically.
The association name in has_many must be plural and match the related model.
You can customize associations with options like class_name and foreign_key.