rippster
rippster

Reputation: 31

ActiveRecord sum per uniq attribute

I have an Active Record of invoices with the attributes :quarter and :revenue. Examples for quarter are "Q1 2015", "Q2 2015", "Q4 2014", etc..

What I want to do is make a map with each :quarter and the sum of :revenue for each unique quarter.

I know how to get a map with each unique :quarter

@bills.map {|bill| bill.quarter}.uniq

and I know how to make a map that sums the :revenue

@bills.map {|bill| bill.revenue}.sum

How can I combine those two?

Upvotes: 1

Views: 299

Answers (1)

Ivan
Ivan

Reputation: 235

You can use a ActiveRecord query directly.

@bills.group(:quarter).sum(:revenue)

Upvotes: 4

Related Questions