在 Rails 中用一个简单的实体引用同一个模型两次?

Referencing the same model twice in Rails with a simple entity?

我有两次引用 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

但我不太清楚在这种情况下如何将它们关联两次

非常感谢任何建议,谢谢。

您实际上不能在这里使用单个关联,因为 ActiveRecord 不支持外键可能在两列之一中的关联。每个 has_one/has_many 对应反面的一个外键列。

相反,对于 Shipment 上的每个外键,您需要一个地址关联:

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_idshipments.address_to_id 上添加唯一性约束并进行验证,否则没有什么可以阻止地址进行多次发货。不确定你为什么想要这个。