Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
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.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda