i have simple app users can view products , preorder them have 1 in stock when released.
a product has many preorders, , many users through preorders.
a user has many preorders, , many products through preorders.
i show other products other people have preordered when view product. i've tried many combinations of joins etc, i'm not sure how wrap head around it.
when viewing product need find users have preordered specific product. need list of products users have preorders for, , ideally ordered number of times have been preordered.
i not sure if answer looking for, i'll try.
product.users # gives users preorders specific product.
for products users have preordered:
user.preorders # give preorders given user.
update
you have product, want more products according users have preordered product, make list of tuples (product, preorders_count).
products = product.users.products # products not defined yet, see below
user model
def self.products # [[pid1, pid2], [pid1], [pid2]] # includes reduce number of queries product_ids = includes(:products).all.map(&:product_ids) # [pid1, pid2] product_ids.flatten!.uniq! # return relation ,so can call product.users.products.where... product.where id: product_ids end
then can use:
products.each |product| product.preorders.size end
suggestion
you can use cached counter preorders in products table
rails g migration add_preorders_count_to_products preorders_count:integer # verify migration rake db:migrate
and in preorder model:
belongs_to :product, counter_cache: true
i have not tested all, can you?
Comments
Post a Comment