rails找到其他客户订购的类似产品

时间:2013-05-05 23:03:36

标签: ruby-on-rails associations

我有一个简单的应用程序,用户可以在其中查看产品并预先订购,以便在发布时有一个库存。

A Product has many preorders, and many users through preorders.

A User has many preorders, and many products through preorders.

我想展示其他人在您查看产品时预订的其他产品。我尝试了很多连接组合等等,但我不知道如何绕过它。

在查看产品时,我需要找到已预订此特定产品的所有用户。然后我需要列出这些用户预订的所有产品,理想情况下,它们将按照预订的次数进行排序。

1 个答案:

答案 0 :(得分:1)

我不确定这是否是您正在寻找的答案,但我会尝试。

product.users # Gives you the users with preorders for that specific product.

对于这些用户预订的所有产品:

user.preorders # will give you all preorders for a given user.

更新

您有一个产品,您希望根据已预订产品的用户获得更多产品,以制作元组列表(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

然后你可以使用:

products.each do |product|
  product.preorders.size
end

建议

您可以在产品表

中使用预先缓存的计数器
rails g migration add_preorders_count_to_products preorders_count:integer
# verify your migration
rake db:migrate

并预购模型:

belongs_to :product, counter_cache: true

我还没有测试过这一切,你呢?

相关问题