0

私は次のテーブルを持っています:

ユーザー:has_many Purchases
アイテム:has_many Purchases

アイテムには「amount」列(+または-)があり、「Item.amounts」の合計が正のすべてのユーザーを見つける必要があります(各ユーザーが行ったすべての購入に対して)。

このクエリはどのように見えますか?(この場合、「SUM」を正しく処理する方法がわかりません。)

私は次のことから始めましたが、明らかに間違っています...(Item.amountが負のアイテムを持つ購入は「含まれません」...)

@users = User.find(:all、
:include => {:purchases =>:item}
、:select => "SUM(item.amount)"、:
order => "..." 、:
conditions => "..."
、:group => "users.id"、
:having => "SUM(item.amount)> 0")

これであなたの助けをありがとう!
トム

4

2 に答える 2

1

これを試して:

User.all(:joins => items, :group => "users.id", 
          :having => "SUM(items.amount) > 0")
于 2010-07-07T20:42:26.417 に答える
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

于 2010-07-07T19:23:06.247 に答える