Rails获得大多数销售产品

时间:2015-11-29 21:11:10

标签: ruby-on-rails arrays postgresql sorting activerecord

我想返回 N 数量最畅销的产品,我的型号:

顺序

has_many :order_items

OrderItem的

belongs_to :order
belongs_to :product
quantity

到目前为止,我有类似的事情,但不包括数量和错误,任何帮助都会很棒。

product.rb

def self.popular
  products = OrderItem.group(:product_id).count
  ids = products.sort_by {|k,v| v}.reverse
  where(id: ids)
end

示例:

[#<OrderItem:0x007fa522727328 id: 1, order_id: 1, product_id: 1, quantity: 3>,
 #<OrderItem:0x007fa5227270a8 id: 2, order_id: 2, product_id: 5, quantity: 4>,
 #<OrderItem:0x007fa522726d88 id: 3, order_id: 2, product_id: 9, quantity: 9>]

期望的输出:

[#<Product:0x007fa5298f9a28 id: 3, title: 'MacBook air'>,
 #<Product:0x007fa5298f9b28 id: 5, title: 'Iphone 6s'>,
 #<Product:0x007fa5298f9c28 id: 1, title: 'Nexus 5'>]

1 个答案:

答案 0 :(得分:1)

刚刚更换了

ids = products.sort_by {|k,v| v}.reverse

ids = products.sort_by {|k,v| v}.reverse.map(&:first)

我在控制台中尝试过,效果很好。

<强>更新

quantity字段的总和排序:

products = OrderItem.group(:product_id).sum(:quantity)
ids = products.sort_by {|k,v| v}.reverse.map(&:first)

<强> UPDATE2:

product模型中添加此方法:

def self.order_by_ids(ids)
  order_by = ["case"]
  ids.each_with_index.map do |id, index|
    order_by << "WHEN id='#{id}' THEN #{index}"
  end
  order_by << "end"
  order(order_by.join(" "))
end

然后:

products = OrderItem.group(:product_id).sum(:quantity)
ids = products.sort_by {|k,v| v}.reverse.map(&:first)
where(id: ids)..order_by_ids(ids)