[英]named_scope to order posts by last comment date
Posts has_many Comments 帖子has_many评论
I'm using searchlogic which will order by named scopes. 我正在使用searchlogic ,它将按命名范围排序。 So, I'd like a named scope that orders by each post's most recent comment.
所以,我想要一个命名范围,按每个帖子的最新评论排序。
named_scope :ascend_by_comment, :order => ...comments.created_at??...
I'm not sure how to do a :joins
and get only the most recent comment and sort by its created_at
field, all in a named_scope
. 我不知道怎么做
:joins
并获取最新的评论并按其created_at
字段排序,所有这些都在named_scope
。
I'm using mysql, fyi. 我正在使用mysql,fyi。
EDIT: 编辑:
This is the SQL query I'd be trying to emulate: 这是我试图模拟的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;
你可以通过范围加入或包含相关的模型来做到这一点,这样的事情就可以了:
named_scope :ascend_by_comment, :joins => :comments, :order => "comments.created_at DESC"
named_scope :ascend_by_comment,
:joins => "LEFT JOIN comments ON comments.post_id = posts.id",
:group => "id",
:select => "posts.*, max(comments.created_at) AS comment_created_max",
:order => "comment_created_max ASC"
You can try to optimize it, but it should work and give you some hints how to do it. 你可以尝试优化它,但它应该工作,并给你一些提示如何做到这一点。
Edit : 编辑 :
After you edited question and shown that you want inner join (no posts without comments?), you can of course change :joins => "..."
with :joins => :comments
. 在您编辑问题并显示您想要内部
:joins => "..."
(没有没有评论的帖子?)之后,您当然可以更改:joins => "..."
with :joins => :comments
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.