# Suming total spend

**URL:** <https://www.ruby-forum.com/t/suming-total-spend/163966>\
**Category:** Rails\
**Created:** [March 26, 2009, 3:03pm UTC](https://www.ruby-forum.com/t/suming-total-spend/163966 "2009-03-26T15:03:35Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ruby\_on\_RailsS\_Talk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/dbc845/32.png) [@Ruby\_on\_RailsS\_Talk](https://www.ruby-forum.com/u/Ruby_on_RailsS_Talk)\
**Post date:** [March 26, 2009, 3:03pm UTC](https://www.ruby-forum.com/t/suming-total-spend/163966/1 "2009-03-26T15:03:35Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Ruby\_on\_RailsS\_Talk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/dbc845/32.png) [@Ruby\_on\_RailsS\_Talk](https://www.ruby-forum.com/u/Ruby_on_RailsS_Talk)\
**Post date:** [March 26, 2009, 4:31pm UTC](https://www.ruby-forum.com/t/suming-total-spend/163966/2 "2009-03-26T16:31:41Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Ruby\_on\_RailsS\_Talk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/dbc845/32.png) [@Ruby\_on\_RailsS\_Talk](https://www.ruby-forum.com/u/Ruby_on_RailsS_Talk)\
**Post date:** [March 26, 2009, 4:44pm UTC](https://www.ruby-forum.com/t/suming-total-spend/163966/3 "2009-03-26T16:44:33Z")

</div>

Thanks!

That’s done the trick perfectly.
