在 rails 查询中获取 has_many 关联的计数

get count of has_many association in rails query

我有两个modelPost 和“评论”。

Post has_may comments.

查询: 我想获得 post.

的最大评论数

这应该通过 rail 查询来完成。

@post = Post.
  joins(:comments).
  select('posts.*, count(comments.id) as comment_count').
  group("posts.id").
  first