Currently I have a Conversation has many Messages
relationship, and a User has many Conversations
relationship.
I would like to create an ActiveRecord Query to get The Last Message of each conversation that a user has.
Let's say I have the conversations ids in an array...
ids = [24, 22, 23]
This query:
Message.where(conversation_id: ids).joins(:conversation).order(created_at: :desc)
... is correct in terms that it returns ALL the Messages across all the user's conversations.
Using the same query above, If I map an array of the conversation_id
s:
Message.where(conversation_id: ids).joins(:conversation).order(created_at: :desc).map(&:conversation_id)
I get an array like this: [24, 24, 22, 22, 23, 22]
that tells me there are 3 messages in conversation with conversation_id=22, 2 messages with conversation_id=24, 1 with conversation_id=23.
This is good, But now my Question now is, How can I create an ActiveRecord Query to get just One Message from each Conversation? (the last one that was created)
I assume I have to use the limit()
/order()
methods, but I have no idea how to do it, it's a little too advanced for me.
Thanks for all your help in advance.