一對一關聯(精確說是一對零或一)透過外鍵在兩張表之間建立唯一對應。典型案例:訂單與發票——每筆訂單最多對應一張發票。
class Order < ActiveRecord::Base has_one :invoice end class Invoice < ActiveRecord::Base belongs_to :order end
關鍵差異在於指派方向決定是否自動儲存:
order.invoice = an_invoice → 發票自動儲存an_invoice.order = order → 訂單不會自動儲存此外,指派既有子物件給 has_one 時,舊關聯的外鍵會被清空(歸零)。
若子物件驗證失敗,ActiveRecord 不會拋出異常也無警告,建議採用:
invoice = Invoice.new # 填寫發票欄位 unless invoice.save! an_order.invoice = invoice # 只有通過驗證才建立關聯 end
belongs_to 宣告詳解預設慣例:父類別名單數混合大小寫,外鍵為 父類別名_id。可傳入 Hash 覆蓋:
class LineItem < ActiveRecord::Base
belongs_to :paid_order,
:class_name => "Order",
:foreign_key => "order_id",
:conditions => "paid_on is not null"
end
產生的實例方法(以 product 為例):
product(force_reload=false):取得關聯物件,快取機制product=(obj):建立關聯,設定外鍵,父儲存時級連儲存子物件build_product(attrs):建構未儲存的關聯物件create_product(attrs):建構並儲存關聯物件has_one 宣告與選項has_one 產生相同方法集,支援 :class_name、:foreign_key、:conditions、:dependent、:order:
:dependent => true:刪除父記錄時自動刪除子記錄:order:指定排序,配合 has_one 可實現「最新一筆」等語意(詳見一對多篇)