如何在rails中的选择查询中添加虚拟"计数"列?

pat*_*ick 1 activerecord ruby-on-rails

我有一个帖子模型,并发布has_many:comments,:as =>:commentable(polymorphic).我正在寻找一种方法,我可以获取所有帖子,并在记录上有一个虚拟属性,它将显示该帖子有多少条评论.

我以为我可以做到:

Post.select("posts.*, count(comments.id) as post_comments").joins(:comments)
Run Code Online (Sandbox Code Playgroud)

但是,它只返回一条记录,post_comments设置为整个数据库中的所有注释,而不仅仅是属于记录的那些...

Luk*_*man 5

实际上,你缺少的是一个群组条款.您需要按站点分组,否则count()聚合会将所有内容折叠为一条记录.

试试这个:

Post.select("posts.*, count(comments.id) as post_comments")
    .joins(:comments)
    .group('posts.id')
Run Code Online (Sandbox Code Playgroud)