Rails 3 :group => :field sorted by created_at desc
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')
精彩评论