T
T
The Whiz2014-03-12 08:41:44
Ruby on Rails
The Whiz, 2014-03-12 08:41:44

Correct association between Order, Product and User in Rails?

Friends, I have a question. I have users, everyone can make many orders , each of which will contain one product. At the moment I have done this:

class Order
  belongs_to :user
  belongs_to :product
end

class Product
  belongs_to :category
  has_many :orders
end

class User
  has_many :orders
end

However, the thought does not let me go that you can go this way:
class User
   has_many :orders
   has_many :products, through: :orders
end

class Order
  belongs_to :user
  belongs_to :product
end

class Product
  belongs_to :category
  has_many :orders
  has_many :users, through: :orders
end

Is it worth it? What is the advantage of the second approach? Which approach is more correct?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
Helsus, 2014-03-12
@modernstyle

So the same thing is written, only with an additive.
And the advantage is that AR in one request will be able to get all users who have bought, for example, a certain product.
Well, just change the naming a little, so that, kmk, it is clearer:

class User
  has_many :orders
  has_many :purchased_products, through: :orders, source: :product

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question