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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With