0

I have a DB schema where a shipment belongs_to two users even though the relation is between model to model.
The shipment can have a receiver_id and a sender_id. Both the receiver & sender are two different records in the same table (the user model).

I was wondering how can I establish a relationship in my rails backend for a shipment to belong_to a record where the user is the sender as well as another record in the same DB where the user is the receiver.
I'v been thinking for ages how to do it, and its very hard to come up with a solution. The only solution I have is to destroy the existing User model, and create two different models: a receiver & a sender. Or is there another solution for this? I've attached my DB schema in this thread.

Any help would much appreciated. Thanks in advance!

DB Schema

Sovalina
  • 5,410
  • 4
  • 22
  • 39
Aly Dabbous
  • 567
  • 1
  • 6
  • 14

1 Answers1

0
class Shipment < ApplicationRecord
  belongs_to :sender, :class_name => "User"
  belongs_to :recipient, :class_name => "User"
end

class User < ApplicationRecord
  has_many :sent_shipments, :class_name => "Shipment", foreign_key: 'sender_id'
  has_many :received_shipments, :class_name => "Shipment", foreign_key: 'recipient_id'
end
Pablo
  • 3,004
  • 1
  • 12
  • 19