Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 需要ActiveRecord分组/计数查询帮助_Ruby On Rails_Activerecord_Count_Group By - Fatal编程技术网

Ruby on rails 需要ActiveRecord分组/计数查询帮助

Ruby on rails 需要ActiveRecord分组/计数查询帮助,ruby-on-rails,activerecord,count,group-by,Ruby On Rails,Activerecord,Count,Group By,我使用的是Rails3 假设我有以下原型:博客、帖子、评论、分类。博客有很多帖子,帖子有很多评论,属于分类 我想知道每个类别中有多少帖子,但只计算那些有评论的帖子 如果我这样做: blog.posts.group("category_id").count --这给了我一个OrderedHash,它接近于我所需要的,但问题当然是计数值包括没有注释的帖子 如果我这样做: blog.posts.group("category_id").joins("comments").count --这给了我该

我使用的是Rails3

假设我有以下原型:博客、帖子、评论、分类。博客有很多帖子,帖子有很多评论,属于分类

我想知道每个类别中有多少帖子,但只计算那些有评论的帖子

如果我这样做:

blog.posts.group("category_id").count
--这给了我一个OrderedHash,它接近于我所需要的,但问题当然是计数值包括没有注释的帖子

如果我这样做:

blog.posts.group("category_id").joins("comments").count
--这给了我该类别帖子中的评论数量(如果我将连接放在分组之前,这会做同样的事情)


感谢您的帮助。

一个简单的选项可以帮助您保持查询的简单性和可读性,那就是在您的评论后关联中设置一个,这样您就可以在其中添加
(“评论计数>0”)
在您的查找中。

一个有助于保持查询简单易读的简单选项是在您的评论后关联中设置一个,这样您就可以在您的查找中添加
where(“评论计数>0”)

尝试一下。很快就把它拼凑起来了

Post.select("posts.id, posts.category_id, count(comments.id)").join(:comments).group('posts.category_id').having('count(comments.id) > 0')
这就意味着

select posts.id, posts.category_id, count(comments.id) from posts join comments on posts.id = comments.post_id group by posts.category_id having count(comments.id) > 0

可能需要对此进行一点迭代…

尝试一下。很快就把它拼凑起来了

Post.select("posts.id, posts.category_id, count(comments.id)").join(:comments).group('posts.category_id').having('count(comments.id) > 0')
这就意味着

select posts.id, posts.category_id, count(comments.id) from posts join comments on posts.id = comments.post_id group by posts.category_id having count(comments.id) > 0

可能需要对此进行一点迭代…

(将“join”更改为“joins”以使其进行编译后)…这将返回每个类别中一篇文章的帖子id和类别id。右-joins。道歉。您需要将“count(comments.id)as foo”添加到返回的post对象中,并表示类别中的注释数。是-该示例围绕所有帖子构建-现在将其范围扩展到您的blog-blog.posts(将“join”更改为“joins”以使其编译)…这将返回每个类别中一篇帖子的帖子id和类别id。右-joins。道歉。您需要将“count(comments.id)as foo”添加到返回的post对象中,并表示类别中的注释数。是的-这个例子是围绕着所有的帖子而设计的-现在把它放到你的博客上-blog.posts.谢谢你的建议。我想我会选择这个选项,但我还是很好奇是否有一些AR方法的组合可以做到这一点。谢谢你的建议。我想我会选择这个选项,但我仍然想知道是否有一些AR方法的组合可以做到这一点。