![](/img/trans.png)
[英]Rails mysql: How to query tables with deeply nested relations(has_many and belongs_to)?
[英]MySQL / Ruby on Rails - How to “SUM” in a :has_many case
我有以下表格:
用户:has_many购买
项目:有许多购买
物料具有“金额”列(可以是+或-),我需要找到所有具有“ SOM.amounts”的正SUM的所有用户(在每个人进行的所有购买中)。
这个查询看起来如何? (在这种情况下,我不确定如何正确处理“ SUM”。)
我从以下内容开始,但是显然,这是错误的……(它不会“包括”商品的Item.amount为负的购买...)
@users = User.find(:all,
:include => {:purchases =>:item},
:select =>“ SUM(item.amount)”,
:order =>“ ...”,
:conditions =>“ ...”,
:group =>“ users.id”,
:having =>“ 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.