帖子 has_many 评论
我正在使用搜索逻辑,它将按命名范围排序。所以,我想要一个按每个帖子的最新评论排序的命名范围。
named_scope :ascend_by_comment, :order => ...comments.created_at??...
我不确定如何做 a:joins
并且只获取最新的评论并按其created_at
字段排序,所有这些都在 a 中named_scope
。
我正在使用mysql,仅供参考。
编辑:
这是我要模拟的 SQL 查询:
SELECT tickets.*, comments.created_at AS comment_created_at FROM tickets
INNER JOIN
(SELECT comments.ticket_id, MAX(comments.created_at) AS created_at
FROM comments group by ticket_id) comments
ON tickets.id = comments.ticket_id ORDER BY comment_created_at DESC;