Rails 中的关联模型和 SUM 查询
我有两个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
抱歉,我刚刚找到了这个问题的答案。我需要将 to_a 添加到 Child 对象的集合中,并调用一个 proc,如下所示:
这很有魅力。
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:
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
It produces one query that does exactly what I need
我遇到了一个问题,孩子委托给父母,我需要找到一笔金额。
给我带来了一个重大的 N+1 问题。解决方案是使用:
I ran into an issue where the child was delegating to the parent and I needed to find a sum.
was giving me a major N+1 problem. The solution was to use: