Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort users by the most recent post?

I have two models: User, and Post which has user_id column (foreign key), and created_at column.

I would like to sort users by the most recent post. For example, if:

user_id = 1, created 3 posts at: 17/05/2011, 19/05/2011, 21/05/2011
user_id = 2, created 1 post at: 22/05/2011
user_id = 3, created 2 posts at: 18/05/2011, 20/05/2011

the result should be:

user_id = 2
user_id = 1
user_id = 3

How would you achieve this in Rails 3 ?

like image 473
Misha Moroshko Avatar asked Oct 11 '22 23:10

Misha Moroshko


1 Answers

Not sure about the RoR part, but you're looking into a group by statement:

select user_id, max(created_at) as created_at
from posts
group by user_id
order by max(created_at) desc
like image 85
Denis de Bernardy Avatar answered Oct 28 '22 15:10

Denis de Bernardy