开发者

Rails 3 :group => :field sorted by created_at desc

开发者 https://www.devze.com 2023-01-26 17:40 出处:网络
How do I select all records grouped by a column sorted by created_at desc. I might want to retrieve all the latest comments for each Articles. No matter what I do the group(:article_id), will a开发者

How do I select all records grouped by a column sorted by created_at desc.

I might want to retrieve all the latest comments for each Articles. No matter what I do the group(:article_id), will a开发者_如何学Golways return the oldest comment.

Best regards. Asbjørn Morell


Something like :

Comment.order('created_at DESC').all

That should do it :)

If you just want the first result, use first instead of all. You also can use limit. Exemple to get the firsts 5 results :

Comment.order('created_at DESC').limit(5).all


You won't find an easy answer with SQL - group happens before sort (since group is generally for aggregate data). Just keep a latest_comment_id field on your Article record, and then join comments on latest_comment_id when you find your articles.

If you want multiple comments per article, you're going to have to resort to either using multiple queries, or maintaining a temp table with just the latest comments per article.


Comment.group(:article_id).order('created_at DESC') 
0

精彩评论

暂无评论...
验证码 换一张
取 消