質問

次の表があります。

ユーザー:has_many購入
アイテム:has_many購入

アイテムには列「量」( +または - )があり、「item.amounts」の正の合計(それぞれが行ったすべての購入)を持っているすべてのユーザーを見つける必要があります。

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

私は次のことから始めましたが、明らかに、それは間違っています...(ネガティブアイテムを持つアイテムを持つ購入を「含める」ことはありません。

@users = user.find(:all、
:include => {:purchases =>:item}、
:select => "sum(item.amount)"、
:order => "..."、
:条件=> "..."、
:group => "users.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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top