列出唯一的订单项及其每日计数

时间:2017-08-17 14:17:34

标签: ruby-on-rails smart-listing

在我的rails应用中,每天都会创建新的订单项。我需要能够让我的smart_listing显示订购了多少苹果和橙子。例如:

  • 订单项数量
  • Apple 2
  • Orange 1

我得到的是:

  • 订单项数量
  • Apple 1
  • Apple 1
  • Orange 1

    line_item_scope = LineItem.all
    line_item_scope = line_item_scope.where(created_at: Date.today.beginning_of_day..Date.today.end_of_day)
    
    if customer_signed_in?
      line_item_scope = line_item_scope.ticket.customer(current_customer.id)
    end
    
    @line_items = smart_listing_create(:line_items, line_item_scope, partial: "line_items/listing2", default_sort: {updated_at: "desc"})
    

我最初的想法是创建一个.map(&:name).uniq但是当我需要关系进入智能列表时会返回一个数组。

1 个答案:

答案 0 :(得分:2)

如果您只需显示LineItem的{​​{1}}以及该名称的项目数,那么name方法可以提供帮助:

group

这将构造一个哈希:

line_item_scope.group(:name).count

然后可以迭代此哈希以显示值:

result = { "Apple" => 2, "Orange" => 1 }

或者可以选择行项目数作为列:

result.each do |name, count|
...
end

然后line_items_scope = LineItem.group(:name) .order(:name) .select("name, COUNT(*) as count") 可以作为line_items_scope

提供给smart_listing_create