Rails 对某些字段进行分组和求和

Rails group collection and sum certain fields

Rails 的新功能,但我找不到此功能!

假设您有一组发票,其中包括 ID、公司名称和发票总额。出于某种原因,有多家公司同名。您想要创建一个 1xn 矩阵,其中每一行都包含具有唯一公司名称的公司数据。

如何将名称相同的公司组合在一起,并将它们的发票总额加在一起。您不关心将哪个 id 保存到该行。只能用Group+Map吗?

例如

[1523, 'Red Roses Inc', 1300.00],
[4126, 'Blue Birds LLC', 110.00],
[846, 'Red Roses Inc', 400.00],

变成

[1523, 'Red Roses Inc', 1700.00],
[846, 'Blue Birds LLC', 110.00],

如果公司和发票合二为一table 比如你的型号是发票

Invoice.group(:company_name).sum(:total)

# sample implementation how to get data and print the result

data_result = Invoice.group(:company_name).sum(:total) 

data_result.each do |v|
  puts "company #{v[0]} total number #{v[1]}"
end

# this will print
# company Red Roses Inc total number 1700
# company Blue Birds LLC total number 110