Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 always return the oldest comment.

Best regards. Asbjørn Morell

like image 912
atmorell Avatar asked Nov 23 '10 10:11

atmorell


1 Answers

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
like image 119
Nicolas Guillaume Avatar answered Oct 29 '22 08:10

Nicolas Guillaume