I have two models:
class User
end
class Message
belongs_to :sender, :class_name=> 'User'
belongs_to :recipient, :class_name=> 'User'
end
I want to fetch all the buddies of a given user ordered by most recent date of message what appears in conversation between given user and his buddy and, if it possible in same query, to fetch the number of message in their conversation.
Now, I'm stuck at this:
Messages.all(:joins => :sender,
:conditions => ['sender_id = ? OR recipient_id = ?', some_user.id, some_user.id],
:select => 'users.*, sender_id, recipient_id, MAX(messages.created_at) as last_created, COUNT(messages.id) as messages_count',
:group => 'messages.sender_id, messages.recipient_id',
:order => 'last_created DESC'
That query produce this output:
a)
users.* | sender_id | recipient_id | MAX(last_created) | messages_count
user1 | 1 | 2 | bla | bla
user1 | 1 | 3 | bla | bla
user1 | 1 | 4 | bla | bla
Because models joined by messages.sender_id = user.id
I have only user1 records fetched but I need user2, user3 and user4 records in that special situation A when user1 has only send messages to his buddies.
b)
users.* | sender_id | recipient_id | MAX(last_created) | messages_count
user2 | 2 | 1 | bla | bla
user3 | 3 | 1 | bla | bla
user4 | 4 | 1 | bla | bla
In situation B, otherwise, i have what i want to have - all three buddies ordered by most recent date of message what appears in conversation between given user and his buddy.
c)
users.* | sender_id | recipient_id | MAX(last_created) | messages_count
user1 | 1 | 2 | bla | bla
user3 | 3 | 1 | bla | bla
user4 | 4 | 1 | bla | bla
Situation C. user2 as buddy of user1 is missing cause :joins => :sender
. Otherwise, if :joins => :recipient
would be missing user3 and user4. Thats the cracker. It's no matter how we join models. How to solve this situation in one query?