首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Ruby on Rails 開發實戰(五十四):ActiveRecord 基礎 - 指定關聯關係

     編輯:Java 相關知識

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

上述宣告會自動為模型新增導航方法,後續章節將逐一深入探討各關聯型態的細節與進階用法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved