Rails选择最受欢迎的产品

时间:2016-05-23 11:40:47

标签: ruby-on-rails ruby-on-rails-4

我需要获得一份最受欢迎的'产品。我认为最好的方法是使用Orders表(模型)引用Products

我知道我应该做什么,但我不知道如何写它。这就是我在MySQL中的表现:

SELECT  products.* 
FROM (SELECT product_id, count(product_id) as count from Orders 
           GROUP BY product_id
           ORDER BY count DESC
           LIMIT 10) AS O
LEFT OUTER JOIN products
ON Products.id  = O.product_id

如何在Rails中编写查询?

例如: Order.group(:product_id).count...

1 个答案:

答案 0 :(得分:1)

尝试

# One single query with join (extract the subquery and 
# assign it to an alias t using active_record function .from)
Product.joins("INNER JOIN t ON t.product_id = products.id")
       .from(
         Order
            .select("orders.product_id, COUNT(orders.id) as count")
            .group("orders.product_id").order("count DESC").limit(10), 
       :t)

# Alternative, but I think it will use 2 queries, 
# and the first one is probably faster
Product
      .where(id: 
      Order
         .select("orders.product_id, COUNT(orders.id) as count")
         .group("orders.product_id").order("count DESC").limit(10).pluck(:product_id))

更新

该代码对我有用(@KazKazar):

Product.joins("INNER JOIN products ON products.id = O.product_id") .from(Order.select("product_id, COUNT(product_id) as count") .group("product_id").order("count DESC").limit(10),:O)