Active Record hỗ trợ 6 loại association:
ruby
# 1:1 — User có 1 profile
class User < ApplicationRecord
has_one :profile
end
class Profile < ApplicationRecord
belongs_to :user # foreign key: user_id trên bảng profiles
end
# 1:N — User có nhiều posts
class User < ApplicationRecord
has_many :posts, dependent: :destroy
end
# N:N — Post có nhiều tags, Tag có nhiều posts
class Post < ApplicationRecord
has_many :post_tags
has_many :tags, through: :post_tags
endQuy tắc foreign key: belongs_to bên nào thì bảng đó chứa foreign key.
has_many :through (3 bảng) dùng khi join table cần thêm attributes. has_and_belongs_to_many (2 bảng) dùng khi join table thuần túy không cần id/attrs.
Active Record supports 6 association types:
ruby
# 1:1 — User has one profile
class User < ApplicationRecord
has_one :profile
end
class Profile < ApplicationRecord
belongs_to :user # foreign key: user_id on profiles table
end
# 1:N — User has many posts
class User < ApplicationRecord
has_many :posts, dependent: :destroy
end
# N:N — Post has many tags, Tag has many posts
class Post < ApplicationRecord
has_many :post_tags
has_many :tags, through: :post_tags
endForeign key rule: whichever side has belongs_to — that table holds the foreign key.
Use has_many :through (3 tables) when the join table needs extra attributes. Use has_and_belongs_to_many (2 tables) for a pure join table without extra attrs.