Rails Associations: How has_many and belongs_to Work
From 1:1 and 1:N to N:M with has_many :through
ActiveRecord Associations declare relationships between models in Ruby code.
Basic relationships:
class User < ApplicationRecord
has_many :posts # User 1:N Post
has_one :profile # User 1:1 Profile
end
class Post < ApplicationRecord
belongs_to :user # posts table has user_id foreign key
has_many :comments
has_many :tags, through: :post_tags # N:M relationship
end
Usage:
user.posts # all posts for this user
user.posts.create(title: '...') # create through association
post.user # the post's author
Options:
dependent: :destroy— delete children when parent is deletedclass_name:— specify relationship class name (non-convention)foreign_key:— specify foreign key column nameinverse_of:— explicitly declare inverse relationship
Architecture Diagram
1:N (has_many / belongs_to)
User
has_many :posts
1 ←→ N
Post
belongs_to :user
user_id foreign key
1:1 (has_one / belongs_to)
User
has_one :profile
1 ←→ 1
Profile
belongs_to :user
user_id foreign key
N:M (has_many :through)
Post
has_many :tags,
through: :post_tags
N
PostTag
post_id + tag_id
N
Tag
has_many :posts,
through: :post_tags
Key point: <strong>Declarative relationship setup</strong> → methods like user.posts, post.user are auto-generated
Key Points
1
belongs_to :user — declares user_id foreign key exists in this table
2
has_many :posts — declares other model has this foreign key
3
has_one :profile — declares 1:1 relationship
4
has_many :tags, through: :post_tags — N:M via join table
5
Set cascade delete with dependent: :destroy
6
Methods like user.posts, post.user auto-generated
Pros
- ✓ Declarative — relationships visible at a glance
- ✓ Auto-generated CRUD methods through associations
- ✓ Solve N+1 with eager loading
- ✓ Minimal config with foreign key conventions
Cons
- ✗ Complex relationships are hard to trace
- ✗ Data loss if dependent option misconfigured
- ✗ Polymorphic associations are complex
- ✗ Need to learn optimization options like counter_cache
Use Cases
User-Post 1:N relationship
Post-Tag N:M relationship
User-Profile 1:1 relationship
Express complex relationships with has_many :through