列出独特的订单项及其每日计数

List unique line items and their daily counts

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

我得到的是:

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

如果您只需要显示 LineItemname 和该名称的项目数,那么 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可以作为ActiveRecordRelation

喂给smart_listing_create