Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only last records grouped by some value in Rails

I have model Message (id, text, sender_id, recipient_id, created_at). I need to get only last records in scope of each recipient_id. It's like in most messangers page with all conversations.

For example, I have this (recipient is current_user):

id, sender_id, created_at
1, 1, 10.04.15
2, 1, 11.04.15
3, 2, 12.04.15
4, 3, 13.04.15
5, 2, 14.04.15

With query I need to get only values with ids 2, 4, 5, grouped by :

id, sender_id, created_at
2, 1, 11.04.15
4, 3, 13.04.15
5, 2, 14.04.15

With this select we have all the records, grouped by user:

Message.order(created_at: :desc).group_by(:sender_id)    
like image 280
Oleg Pasko Avatar asked Dec 29 '25 13:12

Oleg Pasko


1 Answers

You can break down the following on each step to see what the output is:

latest_ids = Message.group(:recipient_id).maximum(:id).values

With the IDs obtained, you might want to fetch the records:

Message.where(id: latest_ids)

Two queries, yes, but this is cleaner than the alternative which might involve writing some SQL yourself.

like image 100
SHS Avatar answered Jan 01 '26 04:01

SHS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!