获取一个类别中所有帖子的最新评论

Num*_*ers 1 postgresql ruby-on-rails ruby-on-rails-4 rails-activerecord postgresql-9.3

评论发布于Post.
帖子属于Category.

我如何获得每个帖子的每个最新更新评论的集合,所有评论都属于一个类别?

我试过这个,但它只给了我一个帖子:

category.posts.joins(:comments).order('updated_at DESC').first
Run Code Online (Sandbox Code Playgroud)

更新

我想要的是每个帖子获取一个提交,每个帖子的最后更新评论.

Dav*_*kin 5

Rails并不是特别好,特别是Postgres禁止明显的解决方案(由@Jon和@Deefour提供).

这是我使用的解决方案,转换为您的示例域:

class Comment < ActiveRecord::Base
  scope :most_recent, -> { joins(
    "INNER JOIN (
      SELECT DISTINCT ON (post_id) post_id,id FROM comments ORDER BY post_id,updated_at DESC,id
    ) most_recent ON (most_recent.id=comments.id)"
  )}
  ...
Run Code Online (Sandbox Code Playgroud)

(DISTINCT ON是SQL标准的Postgres扩展,因此它不适用于其他数据库.)

简要说明:DISTINCT ON删除除第一行之外的所有行post_id.它决定第一个是哪一行,使用ORDER BY必须先开始,post_id然后按顺序updated at DESC获取最新的,然后id作为平局(通常不是必需的).

然后你会像这样使用它:

Comment.most_recent.joins(:post).where("posts.category_id" => category.id)
Run Code Online (Sandbox Code Playgroud)

它生成的查询类似于:

SELECT *
FROM comments
  INNER JOIN posts ON (posts.id=comments.post_id)
  INNER JOIN (
    SELECT DISTINCT ON (post_id) post_id,id FROM comments ORDER BY post_id,updated_at DESC,id
  ) most_recent ON (most_recent.id=comments.id)
WHERE
  posts.category_id=#{category.id}
Run Code Online (Sandbox Code Playgroud)

单一查询,非常高效.如果有人能给我一个不太复杂的解决方案,我会欣喜若狂!