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

I have the Shipping entity that references the Address entity twice, for example:

enter image description here

and the shipment model is as follows belonging twice to the entity of address (address_from, address_to):

class Shipment < ApplicationRecord
  belongs_to :address_from, :class_name => 'Address'
  belongs_to :address_to, :class_name => 'Address'
end

but I’m not very clear how it would look on the other side of the relationship model

class Address < ApplicationRecord
  has_one :shipment
end

If it were a relationship between shipment and address it would be as follows:

rails g model Address

rails g model Shipment address:references

but I am not very clear how to relate them twice in this case

Any advice would be highly appreciated, thanks.

Answer

You can’t actually use a single assocation here as ActiveRecord does not support assocations where the foreign key could be in one of two columns. Each has_one/has_many corresponds to a single foreign key column on the inverse side.

Instead you need one assocation on Address for each foreign key on 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

While you could use has_one here you should note that there is nothing preventing a address from having multiple shipments unless you add uniqueness constraints on shipments.address_from_id and shipments.address_to_id and validations. Not sure why you would want this though.