0

問題:

私の顧客モデルでは、各支払いのステータスが成功でcustomer_id、 が現在のインスタンスの ID または現在のインスタンスの と一致するすべてのトランザクションを合計したいと考えていますparent_id。まず、1 つのクエリですべてを実行しようとしていたため、これをまったく機能させることができませんでした。今、私は探しているものを手に入れましたが、残念ながら私はできる限り効率的ではありません.

環境:

  • 取引テーブルにはcustomer_id列があります
  • 顧客テーブルにはparent_id列があります。
  • 顧客クラスhas_many :transactions
  • トランザクション クラスbelongs_to :customer
  • トランザクション クラスhas_many :payments

ここに私のモデルがあります:

class Customer < ActiveRecord::Base
  has_many :transactions
end

class Transaction < ActiveRecord::Base
  belongs_to :customer
  has_many :payments
end

class Payment < ActiveRecord::Base
  has_one :transaction
end

質問:

これが私が現在使用しているモデル プロパティである場合、そのパフォーマンスを改善するにはどうすればよいでしょうか?

def total_spent
  if customer_type == 1 # "child" customer
    Transaction.joins(:payments).where('payments.status' => 3).sum(:amount, :conditions => ['customer_id = ?', id])
  elsif customer_type == 2 # "parent" customer
    temp_transactions = Transaction.joins(:payments).where('payments.status' => 3)
    temp = temp_transactions.sum(:amount, :conditions => ['customer_id = ?', id])
    Customer.find_all_by_parent_group_id(id).each do |c|
      temp = temp + temp_transactions.sum(:amount, :conditions => ['customer_id = ?', c.id])
    end
    temp
  end
end
4

1 に答える 1

1
Transaction.joins(:payments)
   .joins(:customer)
   .where(:payments => {:status => 3})
   .where("customers.id = ? or customers.parent_id = ?", 5, 5)
   .sum(:amount)


SELECT SUM(amount) AS sum_id 
FROM "transactions" 
    INNER JOIN "payments" ON "payments"."transaction_id" = "transactions"."id" 
    INNER JOIN "customers" ON "customers"."id" = "transactions"."customer_id" 
WHERE 
   "payments"."status" = 3 
   AND (customers.id = 5 or customers.parent_id = 5)
于 2013-02-23T02:37:03.303 に答える