MySQL / Ruby在Rails上 - 如何在A:HAS_MANY CASE中“求和”
-
02-10-2019 - |
题
我有以下表:
用户:has_many购买
项目:has_many购买
项目具有“金额”(可以为 +或 - )的列,我需要找到所有具有“ item.Amounts”的正总和的用户(在每个购买的所有购买中,每个人都进行了)。
这个查询看起来如何? (在这种情况下,我不确定如何正确处理“总和”。)
我从以下内容开始,但是显然,这是错误的...(它不会“包含”带有负面项目的物品的购买。
@users = user.find(:all,
:include => {:publate =>:item},
:select =>“ sum(item.amount)”,
:order =>“ ...”,
:条件=>“ ...”,
:group =>“ user.id”,
:have =>“ sum(item.amount)> 0”)
感谢您的帮助!
汤姆
解决方案
试试这个:
User.all(:joins => items, :group => "users.id",
:having => "SUM(items.amount) > 0")
其他提示
听起来这是某些模型方法的好情况。
我没有测试这个,但我认为您想做类似以下操作:
class User < ActiveRecord::Base
has_many :purchases
has_many :items, :through => :purchases
def items_total
#get all the items iterate over them to get the amount,
#compact to get rid of nils
#and reduce with a sum function to total and return
items.all.each{|item| item.amount}.compact.reduce(:+)
end
然后
User.items_total
不隶属于 StackOverflow