Rails将数据分组并呈现为json

时间:2011-01-17 03:27:57

标签: ruby-on-rails json group-by sum

我有一个包含许多优惠券的用户模型。每张优惠券都有一个价值。

我想检索有关所有用户优惠券的一些数据,例如每个用户的所有优惠券价值的总和。我也希望白天对数据进行分组。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

有一种名为sum的方法可用于关联。例如:

@user.coupons.all.sum(&:value)

在这种情况下,value是您想要求和的属性。

并按日期对这些进行分组,那么可能是这样的:

#group_by will create a hash with the dates as keys and place the coupons in arrays
@coupons = @user.coupons.all.group_by{ |coupon| coupon.created_at.strftime("%D") }

#Loop through all keys (dates) and get the sum of the coupons
@coupons.keys.each |date|
  puts "Date: #{date}, Value: #{@coupons[date].sum(&:value)}"
end