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
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---
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
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---
Thanks! That''s done the trick perfectly. On Mar 26, 3:30 pm, "David T." <jellyrol...-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> 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--~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---