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.