Rails 中的关联模型和 SUM 查询

发布于 2024-10-06 03:49:48 字数 411 浏览 1 评论 0原文

我有两个 Rails 模型,一个 Child 和一个 Parent 。

我知道我可以做到这一点:

Child.sum(:income, :conditions => "parent_id = #{@parent_id}")

但我希望能够做到这一点:

Parent.children.sum(:income)

但是如果我尝试的话,这会给我错误的价值观。有没有更简洁的写法

Child.sum(:income, :conditions => "parent_id = #{@parent_id}")

TIA

【ps:Rails 3开发环境】

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]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

伴随着你 2024-10-13 03:49:48

抱歉,我刚刚找到了这个问题的答案。我需要将 to_a 添加到 Child 对象的集合中,并调用一个 proc,如下所示:

Parent.children.to_a.sum(&:income)

这很有魅力。

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.

妥活 2024-10-13 03:49:48

很抱歉撞到旧线程,但我想我找到了更好(最好?)的解决方案。下面是我最终完成的项目的代码

self.purchases.where(:script_id => script_id, :approved => true).sum(:instances)

,它生成一个完全符合我需要的查询

SELECT SUM("purchases"."instances") AS sum_id FROM "purchases" WHERE "purchases"."customer_id" = 1 AND "purchases"."script_id" = 1 AND "purchases"."approved" = 't'

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'
皓月长歌 2024-10-13 03:49:48

我遇到了一个问题,孩子委托给父母,我需要找到一笔金额。

children.to_a.sum(:parent_income)

给我带来了一个重大的 N+1 问题。解决方案是使用:

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

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文