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 get all the friends of a certain user, sorted by the latest date of the message that appears in the conversation between this user and his friend , and, if possible in the same request, the number of messages in their conversation.
Now I'm stuck on 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'
This query produces this output:
and)
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
Since the models connected using messages.sender_id = user.id, I only have user1 entries, but I need user2, user3 and user4 entries in this special situation A, when user1 only sends messages to his friends.
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
B, , , - , .
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
C. user2 user1 :joins => :sender. , :joins => :recipient user3 user4. . , . ?