查找超过定义数量的评论的所有帖子

KJF*_*KJF 5 activerecord ruby-on-rails

我有一个简单的rails 3博客应用程序,其中帖子有很多评论和评论属于一个帖子.

我想创建一个范围来获取所有超过5条评论的帖子.没有计数器缓存列的最佳方法是什么?

noo*_*odl 8

像这样,也许吧?

Post.select('posts.*, count(comments.id) as comment_count').
  joins(:comments).
  group('posts.id').
  having('comment_count > 5')
Run Code Online (Sandbox Code Playgroud)


dan*_*ans 5

Postgres 9.1中,我不得不设置这样的东西,因为postgres不喜欢在计算字段上添加条件或类似的东西.

Post.select('posts.*, count(comments.id) as comment_count').
  joins(:comments).
  group('posts.id').
  having('count(comments.id) > 5')
Run Code Online (Sandbox Code Playgroud)