Rails Group data and render as json
I have a User model with many coupons. Each coupon has a value.
I would like to retrieve some data about all the user coupons, like the sum of the value of all the coupons for each开发者_StackOverflow user. I also would like to group data by day.
How can I do this?
There is a method called sum that can be used on the associations. For example:
@user.coupons.all.sum(&:value)
In this case value is the attribute you want to sum.
And to group these by date, then perhaps something like this:
#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
精彩评论