我有兩次參考 Address 物體的 Shipping 物體,例如:

并且發貨模型如下兩次屬于地址物體(address_from,address_to):
class Shipment < ApplicationRecord
belongs_to :address_from, :class_name => 'Address'
belongs_to :address_to, :class_name => 'Address'
end
但我不太清楚它在關系模型的另一邊會是什么樣子
class Address < ApplicationRecord
has_one :shipment
end
如果是貨件和地址之間的關系,則如下所示:
rails g model Address
rails g model Shipment address:references
但我不太清楚在這種情況下如何將它們關聯兩次
任何建議將不勝感激,謝謝。
uj5u.com熱心網友回復:
您實際上不能在這里使用單個關聯,因為 ActiveRecord 不支持外鍵可能位于兩列之一的關聯。每個has_one/has_many對應于反面的單個外鍵列。
相反,對于 Shipment 上的每個外鍵,您都需要一個 Address 關聯:
class Shipment < ApplicationRecord
belongs_to :address_from,
class_name: 'Address',
inverse_of: :outgoing_shipments
belongs_to :address_to,
class_name: 'Address',
inverse_of: :incoming_shipments
end
class Address < ApplicationRecord
has_many :outgoing_shipments,
class_name: 'Shipment',
foreign_key: :address_from_id,
inverse_of: :address_from
has_many :incoming_shipments,
class_name: 'Shipment',
foreign_key: :address_to_id,
inverse_of: :address_to
end
雖然您可以has_one 在這里使用,但您應該注意,除非您在shipments.address_from_id和shipments.address_to_id和驗證上添加唯一性約束,否則不會阻止地址多次發貨。不知道為什么你會想要這個。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/376644.html
標籤:红宝石轨道 红宝石 关系 rails-activerecord
上一篇:如何從物件創建陣列并只保留正值?
