Rails 3 ActiveRecord sum of a model for each associated model

懵懂的女人 提交于 2019-12-24 00:17:11

问题


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 caterogies 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]].


回答1:


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, ...}



回答2:


@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}]}


来源:https://stackoverflow.com/questions/6685601/rails-3-activerecord-sum-of-a-model-for-each-associated-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!