开发者

Associated models and SUM query in Rails

开发者 https://www.devze.com 2023-01-28 19:21 出处:网络
I\'ve got t开发者_如何学运维wo Rails models, a Child and a Parent say. I know that I can do this:

I've got t开发者_如何学运维wo 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'


I ran into an issue where the child was delegating to the parent and I needed to find a sum.

children.to_a.sum(:parent_income)

was giving me a major N+1 problem. The solution was to use:

children.joins(:parent).sum(:income)


I also ran into a similar situation, here was the solution in rails 4 with also checking if items being tallied were active or inactive. I ran this in the model before save.

order_items.collect { |oi| oi.valid? ? (oi.quantity * oi.price) : 0 }.sum
0

精彩评论

暂无评论...
验证码 换一张
取 消