Forum: Ruby on Rails Suming total spend

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dc372593c8ad1d324033652008f706ee?d=identicon&s=25 Ruby on Rails: Talk (Guest)
on 2009-03-26 15:03
(Received via mailing list)
Hi

I have an application with a number of models. The one's I'm
interested in are customers, who have appointments. Each appointment
has a number of treatments associated.

I'm trying to calculate the total amount spent by the customer on
treatments over all the appointments.

@cust = Customer.find(1)
@cust.appointments[0].treatments.sum(:price)

The above works for just the first appointment found. But how to I get
it to sum across all appointments?

I've tried something like:

@total = @cust.appointments.sum{|u| u.treatments.sum(:price)}

But to no avail.

Any help would be gratefully appreciated!

Darren
9a552735a02d1ae44cb37e8d8ea9037c?d=identicon&s=25 David T. (Guest)
on 2009-03-26 16:31
(Received via mailing list)
How about using sum conditions / includes to do it all in one SQL
query.  Something like:

@total = Treatment.sum(:price, :include => :appointment, :conditions
=> {'appointments.customer_id' => @cust.id})

David
Dc372593c8ad1d324033652008f706ee?d=identicon&s=25 Ruby on Rails: Talk (Guest)
on 2009-03-26 16:44
(Received via mailing list)
Thanks!

That's done the trick perfectly.
This topic is locked and can not be replied to.