Rails 支援三種基本表間關聯,需在模型中宣告對應的巨集方法:
| 關聯類型 | 典型案例 | 宣告方式 |
|---|---|---|
| 一對一 | 訂單 ↔ 發票 | has_one :invoice / belongs_to :order |
| 一對多 | 訂單 ↔ 明細項目 | has_many :line_items / belongs_to :order |
| 多對多 | 商品 ↔ 分類 | has_and_belongs_to_many :categories / has_and_belongs_to_many :products |
# 一對一 class Order < ActiveRecord::Base has_one :invoice end class Invoice < ActiveRecord::Base belongs_to :order end # 一對多 class Order < ActiveRecord::Base has_many :line_items end class LineItem < ActiveRecord::Base belongs_to :order end # 多對多 class Product < ActiveRecord::Base has_and_belongs_to_many :categories end class Category < ActiveRecord::Base has_and_belongs_to_many :products end
上述宣告會自動為模型新增導航方法,後續章節將逐一深入探討各關聯型態的細節與進階用法。