Reputation: 3451
I have a simple app where users can view products and preorder them so they have one in stock when they get released.
A Product has many preorders, and many users through preorders.
A User has many preorders, and many products through preorders.
I would like to show other products that other people have preordered to when you view a product. I've tried many combinations of joins where etc, but I'm not sure how to wrap my head around it.
When viewing a product I need to find all the users who have preordered this specific product. Then I need to list all of the products those users have preorders for, and ideally they would be ordered by the number of times they have been preordered.
Upvotes: 0
Views: 308
Reputation: 21803
I am not sure if this is the answer you are looking for, but I'll try.
product.users # Gives you the users with preorders for that specific product.
For all products those users have preordered:
user.preorders # will give you all preorders for a given user.
You have a product, you want to get more products according users who have preordered product, to make a list of tuples (product, preorders_count).
products = product.users.products # products not defined yet, see below
def self.products
# [[pid1, pid2], [pid1], [pid2]]
# includes to reduce the number of queries
product_ids = includes(:products).all.map(&:product_ids)
# [pid1, pid2]
product_ids.flatten!.uniq!
# return a relation ,so you can call product.users.products.where...
Product.where id: product_ids
end
Then you can use:
products.each do |product|
product.preorders.size
end
You can use a cached counter for preorders in products table
rails g migration add_preorders_count_to_products preorders_count:integer
# verify your migration
rake db:migrate
and in preorder model:
belongs_to :product, counter_cache: true
I have not tested this all, can you?
Upvotes: 1