D
D
Dmitry2015-12-18 16:45:41
Ruby on Rails
Dmitry, 2015-12-18 16:45:41

How to make two foreign keys in one table?

Ruby on Rails
has two tables:

Users:
id
name

Orders:
id
buyer
seller

In the table with orders (Orders), the user id is stored in the buyer and seller
fields. Tell me, how to set such a relationship in the models?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zaporozhchenko Oleg, 2015-12-18
@1diem

Examples for the answer nbekseitov

class Buyer < User
end

class Seller < User
end

class Order
  belongs_to :buyer
  belongs_to :seller
end

class Order
  belongs_to :buyer, foreign_key: :buyer_id, class_name: User
  belongs_to :seller, foreign_key: :seller_id, class_name: User
end

It is difficult to say which option is correct, it depends on the task and the structure of the project. The second option is much simpler and quite often sufficient. In the first option, from the very beginning you will explicitly separate the logic of the seller and the buyer between the two classes, which will positively affect the quality of the code in the future.

N
N. Bekseitov, 2015-12-18
@nbekseitov

Polymorphic relationships or foreign_key

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question