@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!
Check this. It should work. If any errors, ping me, I will update it
PS: your code is not optimized at all. All of this could be done with single SQL query, but the logic is pretty hard to write this query without debugging
10
solved Rails: Remove Curly Braces in Array [closed]