Reputation: 6674
I have a query:
@clients = Client.where(location_id: location).includes(:check_ins, :payments, :purchases).where("check_ins.created_at > ?", start_date).references(:check_ins)
that returns an ActiveRecord::Relation
array of clients
. Each client has_many :payments
and each payment has an :amount
.
For each client in the ActiveRecord::Relation
, I'd like to include the sum of their payment amounts client.payments.sum(:amount)
. How can I get that returned in the array?
Upvotes: 0
Views: 483
Reputation: 6603
You can just always write a helper method:
class Client
has_many: payments
def total_payment_amount
payments.sum(:amount)
end
end
Then in your given code, you could just call it like the following or whereever you are gonna call it (like in the views for example):
@clients = Client.where(location_id: location).includes(:check_ins, :payments, :purchases).where("check_ins.created_at > ?", start_date).references(:check_ins)
@clients.each do |client|
puts client.total_payment_amount
end
Or, if you actually instead want this value as part of the SQL so that you can even query on this further then:
class Client < ApplicationRecord
has_many :payments
end
Then in your given code:
@clients = Client.select('SUM(payments.amount) AS total_payment_amount').joins(:payments)
@clients.each do |client|
puts client.total_payment_amount
end
Upvotes: 1