列出独特的订单项及其每日计数
List unique line items and their daily counts
在我的 rails 应用中,每天都会创建新的订单项。我需要能够让我的 smart_listing 显示订购了多少苹果和橙子。例如:
- 订单项数量
- 苹果 2
- 橙色 1
我得到的是:
- 订单项数量
- 苹果 1
- 苹果 1
橙色 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 但 returns 当我需要关系进入智能列表时创建一个数组。
如果您只需要显示 LineItem
的 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
可以作为ActiveRecordRelation
喂给smart_listing_create
在我的 rails 应用中,每天都会创建新的订单项。我需要能够让我的 smart_listing 显示订购了多少苹果和橙子。例如:
- 订单项数量
- 苹果 2
- 橙色 1
我得到的是:
- 订单项数量
- 苹果 1
- 苹果 1
橙色 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 但 returns 当我需要关系进入智能列表时创建一个数组。
如果您只需要显示 LineItem
的 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
可以作为ActiveRecordRelation
smart_listing_create