Rails的模型的3 ActiveRecord的总和各相关型号 [英] Rails 3 ActiveRecord sum of a model for each associated model
本文介绍了Rails的模型的3 ActiveRecord的总和各相关型号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个型号
分类
- ID
- 名称
和
交易
- ID
- CATEGORY_ID
- 量
我要找到每个类别中的所有交易的总和。 我知道我能得到caterogies的列表,然后得到的总和都用CATEGORY_ID的交易,但它会做20+的查询。
有没有办法做到这一切在一个查询?
编辑:我想结束了[类别1,总和],[类别2,总和]列表。
解决方案
Transaction.group(:CATEGORY_ID).SUM(:数额)
这将返回类似这样的哈希值:
{CATEGORY_ID => SUM_OF_TRANSACTIONS,...}
或
{1 => 100.0,2 => 350.0等}
要获得实际类别
名称:
Transaction.includes(:类)。集团(categories.name)和(:数额)
#=> {组别=> 100.0,...}
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]].
解决方案
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, ...}
这篇关于Rails的模型的3 ActiveRecord的总和各相关型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文