Try this:
message_per_uniq_receiver = @user.sent_messages.select('DISTINCT ON (receiver_id) *')
.order('receiver_id, messages.created_at DESC')
message_per_uniq_sender = @user.received_messages.select('DISTINCT ON (sender_id) *')
.order('sender_id, messages.created_at DESC')
This DISTINCT ON
is kinda complex ( documentation here ):
Long story short, the DISTINCT ON(sender_id)
will create groups for each distinct sender_id
found in the messages table, and will select the first of each group, the first of the group is determined by the ORDER BY
clause.