如何使用ActiveRecord返回父级唯一的最新子级

时间:2018-02-02 10:29:24

标签: ruby-on-rails postgresql activerecord ruby-on-rails-5

发表has_many条评论。评论belongs_to发表评论。我试图找回最近评论的列表,但每个帖子只有一个。

以下SQL返回PostgreSQL中设置的正确注释结果:

SELECT
  comments.*
FROM
  (SELECT
     post_id, MAX(created_at) AS created_at
   FROM
     comments
   GROUP BY
     post_id) AS latest_comments
INNER JOIN
  comments
ON
  comments.post_id = latest_comments.post_id AND
  comments.created_at = latest_comments.created_at

如何定义查询以使用ActiveRecord返回相同的结果集?

1 个答案:

答案 0 :(得分:1)

这并不等同于您的SQL,但我相信也应该有效:

Comment.where(
  created_at: Comment.select('max(created_at)').group(:post_id)
)
# Comment Load (6.9ms)  SELECT  "comments".* FROM "comments" WHERE "comments"."created_at" IN (
#   SELECT max(created_at) FROM "comments" GROUP BY "comments"."post_id"
# ) LIMIT $1  [["LIMIT", 11]]