Ruby on Railsプロジェクト4.0では、私はPayments
モデルhas_many
Transactions
モデルを持っています。特定の条件に一致するモデルが関連付けられているモデルの合計属性
私は今、次のデータ
SELECT * FROM payments;
id | paid_amount
---+--------------
1 | 200
2 | 300
3 | 100
4 | 400
5 | 100
6 | 600
7 | 100
8 | 100
9 | 800
SELECT * FROM transactions;
id | payment_id | type
---+-------------+------
1 | 2 | cash
2 | 3 | credit
3 | 1 | credit
4 | 4 | cash
5 | 1 | cash
6 | 6 | credit
7 | 1 | cash
8 | 1 | credit
9 | 8 | cash
をお持ちの場合は
> Payment.where(id: Transaction.where(type: 'cash').pluck(:payment_id)).sum(:paid_amount)
> 1000
> # The sum of paid_amount from payments with ids 1, 2, 4 and 8
を次のように、私は、特定のタイプのトランザクションを持っている
Payments
から数値属性
paid_amount
、の合計を計算しています
しかし、これは何千ものレコードで十分に速く動作しないので、私はincludes
でこれを達成しようとしました。
> Payment.includes(:transactions).where("transactions.type = 'cash'").sum(:paid_amount)
> 1200
> # paid_amount of payment with id 1 is considered two times because of transactions with id 5 and 7
私は必要な数をどのように計算すればよいですか?