[英]Rails sum on an associated record
I have a survey model that works like so: 我有一个像这样的调查模型:
ResponseSets have many Responses
ResponseSets有很多响应
Responses belong_to Answer回复归属感
Answer model has a "value" column.答案模型具有“值”列。
Given a ResponseSet, I'd like the sum of the Answers that are associated with each Response. 给定一个ResponseSet,我想要与每个Response相关联的Answers之和。
Ie, what I'd like to be able to do, (in imaginary code) is: 也就是说,我想什么,能够做,(在虚代码)是:
response_set.responses.answers.sum('value')
However, this obviously doesn't work, I need to build a query through response_set.responses
, but I don't know how. 但是,这显然不起作用,我需要通过
response_set.responses
建立一个查询,但是我不知道如何。
What's the SQL-fu way to tackle this in ActiveRecord? 在ActiveRecord中解决此问题的SQL-fu方法是什么?
好吧,如果您使用的是Rails 3.2,则可以执行以下操作:
response_set.responses.answers.pluck(:value).inject{|sum,x| sum + x }
Are the answers Integers, in the sense that you're looking to find ALL numeric answers associated with a response and literally add them all up? 从某种意义上来说,答案是整数吗?您正在寻找与答案相关的所有数字答案,并将它们全部相加吗? I think you could use map and inject for something like this, depending exactly on how your models/associations are set up..
我认为您可以使用map并注入类似的内容,具体取决于您的模型/关联的设置方式。
response_set.responses.answers.map(:&value).inject(:+)
Can you post your models? 您可以发布模型吗?
After much trial and error I came up with this relatively simple solution, I hope this helps others in the future: 经过反复试验,我想出了一个相对简单的解决方案,希望以后对其他人有所帮助:
response_set.responses.joins(:answer).sum('answers.value')
To make this more convenient I just made this a method in the ResponseSet
Model: 为了使此操作更加方便,我在
ResponseSet
模型中将此方法ResponseSet
:
def total_value
self.responses.joins(:answer).sum('answers.value')
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.