Rails 3 ActiveRecord sum of a model for each associated model
I have 2 models
Category
- id
- name
and
Transaction
- id
- category_id
- amount
I want to find the sum of all transactions for each category. I know I can get a list of cater开发者_Python百科ogies and then get the sum for all the transactions with the category_id but it will do 20+ queries.
Is there a way to do it all in one query?
Edit: I want to end up with a list of [[category1, sum], [category2, sum]].
Transaction.group(:category_id).sum(:amount)
This will return a hash similar to this:
{CATEGORY_ID => SUM_OF_TRANSACTIONS, ....}
or
{1 => 100.0, 2 => 350.0, etc.}
To get the actual Category
names:
Transaction.includes(:category).group("categories.name").sum(:amount)
# => {"Category1" => 100.0, ...}
@category.transactions.sum(:amount)
UPD 1
you can share some job with Ruby:
Category.includes(:transactions).map{|c| [c.name, c.transactions.inject(0){|sum, t| sum += t.amount}]}
精彩评论