简体   繁体   English

关联记录上的Rails总和

[英]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.

相关问题 Rails 3 HABTM通过记录关联模型属性查找 - Rails 3 HABTM find by record associated model attribute Active Record:基于两个关联表的总和查找集合 - Active Record: Find collection based on sum of two associated tables Rails 活动记录按列的总和排序 - Rails active record order by sum of a column Rails has_many关联记录符合条件的地方 - Rails has_many where associated record meets a criteria Rails 5:如果结果与特定记录相关联,则查询将不包括在内 - Rails 5: Query which excludes results if they're associated with a specific record 将表的每个记录中的整数字段与另一个表中的相关记录的总和进行比较 - Comparing an integer field in each record of a table to the sum of associated records in another table 包括与在 Ruby on Rails 中使用搜索时找到的记录关联的所有记录 - Include all records associated with a record that has been found when search is used in Ruby on Rails Rails-查找仅具有一个特定关联的has_many或has_and_belongs_to_many记录的记录 - Rails - Find records with only one specific associated has_many or has_and_belongs_to_many record 选择与其他记录不相关的记录 - Select records that are not associated with the other record 删除数据库记录和关联图像 - Delete a database record and associated image
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM