Below this section is my original answer; I mis-read the question and thought the OP only wanted a list of users who had RECEIVED messages from the specified user; I didn't notice the part about also users who SENT messages to the specified user as well. Here is my update. I'll leave the original answer below in case it helps.
In this version of the answer, I would alter the join and the where clause so that the query examines either the sender_id
or recipient_id
column:
User.joins("INNER JOIN messages ON (messages.sender_id = users.id OR messages.recipient_id = users.id)")
.where("messages.sender_id = ? OR messages.recipient_id = ?", current_user.id, current_user.id).uniq
Apologies for the misunderstanding.
ORIGINAL ANSWER:
In order to get all the users you've contacted, I am thinking the easiest approach is to do this through the normal active record query methods. First, set up the has_many
in your User
model like so:
In your User
model
has_many :messages_sent, class_name: "Message", foreign_key: :sender_id
has_many :messages_received, class_name: "Message", foreign_key: :recipient_id
And then, you can simply query using the relationship like so:
User.joins(:messages_received).where(:messages=>{sender_id: current_user.id}).uniq
Note: replace current_user
with whatever you use to store the target user.
Edit
Someone asked why this is better than using the direct :messages_sent
relationship. The advantage this approach has is that it is all done on the database level, where proper indexing can do its job. If you have a very large table, and this user has sent a large number of messages, using the active record has_many
relationship will require you to iterate over a large collection, attempting to find unique users.
Just to add a bit more clarification, this query should render an SQL query that looks something like this:
SELECT users.*
FROM users INNER JOIN messages ON messages.recipient_id = users.id
WHERE messages.sender_id = 1
In plain English, this is basically saying to the database: "Please give me all the users who RECEIVED a message SENT by user #1".