問題:
私の顧客モデルでは、各支払いのステータスが成功で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