我有以下代码:
@temp = SalesOrder.where("status > ?", 0).ids
items = SalesOrderItem.where(sales_order_id: @temp).where.not(product_id: nil)
total = items.to_a.group_by(&:product_id).map do |product_id, quantity|
{:product_name => Product.find(product_id.to_i).name,
:quantity => quantity.sum { |q| q.quantity.to_f } }
end
@top_five = total.sort_by { |h| h[:quantity] }.reverse!
@top_five
生成此数组:
[{:product_name => "Six", :quantity => 1300.0},
{:product_name => "Plastic Tumbler 620ml", :quantity => 1205.0},
{:product_name => "Product Four", :quantit y=> 1110.0},
{:product_name => "Product Five", :quantity => 510.0},
{:product_name => "Fiber Optic Cable", :quantity => 200.0}]
我需要它采用这种格式
{"Football" => 10, "Basketball" => 5}
或者
[["Football", 10], ["Basketball", 5]]
答案 0 :(得分:2)
@temp = SalesOrder.where("status > ?", 0).ids
items = SalesOrderItem.where(sales_order_id: @temp).where.not(product_id: nil)
total = items.to_a.group_by(&:product_id).each_with_object({}) do |(product_id, quantity), total|
total[Product.find(product_id.to_i).name] = quantity.map(&:quantity).map(&:to_f).sum
end
@top_five = total.sort_by { |k, v| v }.reverse!
检查一下。它应该工作。如果有任何错误,请ping我,我会更新它
PS:您的代码根本没有优化。所有这些都可以通过单个SQL查询来完成,但是在没有调试的情况下编写此查询非常困难