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

How to select all records grouped by column sorted by create_at desc.

I would like to get all the latest comments for each article. No matter what I do, the group (: article_id) will always return the oldest comment.

Sincerely. Asbjorn Morell

+5
source share
3 answers

You will not find a simple answer with an SQL group that happens before sorting (since the group is usually intended for aggregate data). Just save the field latest_comment_idin your article, and then attach the comments to latest_comment_id when you find the articles.

, .

+3

- :

Comment.order('created_at DESC').all

:)

, first all. limit. , 5 :

Comment.order('created_at DESC').limit(5).all
+16
Comment.group(:article_id).order('created_at DESC') 
+1
source

All Articles