9
9
9karamba2019-04-21 19:12:49
Ruby on Rails
9karamba, 2019-04-21 19:12:49

Displaying products from multiple categories?

At me the user can subscribe to categories. I want to place on the main page all the products from the categories that a person subscribes to. Subscription using the Subscription helper model, which stores the user_id and category_id.
How can I do it? In which direction to look for information about this?
The only thing I found is if all the user's subscriptions are stored in his table. But I don't think it's good

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
oh_shi, 2019-04-22
@oh_shi

If you write all the associations in the models, then you can then get a list of products through @user.products. Inside, there are several INNER JOIN, and as an alternative, you can make such a request yourself.

class User < ApplicationRecord
  has_many :subscriptions
  has_many :categories, through: :subscriptions
  has_many :products, through: :categories
end

class Subscription < ApplicationRecord
  belongs_to :user
  belongs_to :category
  has_many :products, through: :categories
end

class Category < ApplicationRecord
  has_many :subscriptions
  has_many :products
end

class Product < ApplicationRecord
  belongs_to :category
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question