I've got two Rails models, a Child and a Parent say.
I know that I can do this:
Child.sum(:income, :conditions => "parent_id = #{@parent_id}")
But I want to be able to do this:
Parent.children.sum(:income)
But this is giving me the wrong values if I try it. Is there a more concise way of writing
Child.sum(:income, :conditions => "parent_id = #{@parent_id}")
?
TIA
[ps: Rails 3 dev environment]
Sorry but I have just found out the answer to this. I needed to add to_a to the collection of Child objects, and call a proc, as so:
Parent.children.to_a.sum(&:income)
This works a charm.
Sorry for bumping up an old thread, but I think I found better(best?) solution. Below is code for my project that I ended up
self.purchases.where(:script_id => script_id, :approved => true).sum(:instances)
It produces one query that does exactly what I need
SELECT SUM("purchases"."instances") AS sum_id FROM "purchases" WHERE "purchases"."customer_id" = 1 AND "purchases"."script_id" = 1 AND "purchases"."approved" = 't'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With