๐
Associations
has_many, belongs_to โ defining relationships between models
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