Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associated models and SUM query in Rails

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]

like image 653
The Pied Pipes Avatar asked Dec 05 '10 20:12

The Pied Pipes


2 Answers

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.

like image 79
The Pied Pipes Avatar answered Sep 21 '22 21:09

The Pied Pipes


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'
like image 20
ZuBB Avatar answered Sep 22 '22 21:09

ZuBB