通过使用Rails 3个孩子的计数过滤器 [英] Filter by count of children using Rails 3

查看:267
本文介绍了通过使用Rails 3个孩子的计数过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要选择具有使用Rails 3和一个查询一个或更多的评论文章。

I'd like to select posts that have one or more comments using Rails 3 and a single query.

我想是这样的:

Post.includes(:comments).where('count(comments.id)>0')

不过,我得到这个错误:

However I get this error:

ActiveRecord::StatementInvalid: PGError: ERROR:  aggregates not allowed in WHERE clause

我GOOGLE了这一点,类似的方法,按等,没有运气。任何帮助将AP preciated。

I've googled this and similar approaches, group by, etc with no luck. Any help will be appreciated.

推荐答案

我敢肯定,你可能已经想通了这一点了,但我相信你要找的是什么的有(:条件)的关系,何塞。

I'm sure you may have figured this out by now, but I believe what you're looking for is the having(:conditions) relationship, Jose.

Post.includes(:comments).having(:conditions => "count(comments.id) > 0")

我没有测试过code所以,请把它与一粒盐,但你一定要能够从那里跳开始。

I haven't tested that code so please take it with a grain of salt, but you should definitely be able to jump start from there.

这篇关于通过使用Rails 3个孩子的计数过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆