1

I have the following model:

Message.rb: sender_id, receiver_id, created_at

I would like to find all messages where the sender_id and receiver_id are both within an array of ids [1,4,41,543,312,62,234]. I would then like to group all the messages by the pair (sender_id & receiver_id) ordered by created_at.

Is this the right way to write the query? I am looking for an optimal solution here.

Message.where("sender_id IN ? AND receiver_id IN ?", @ids) 

1 Answer 1

1

Try:-

Message.where("sender_id IN (?) AND receiver_id IN (?)", @ids, @ids).order("created_at ASC")
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but does that group by sender_id and receiver_id before the order by created_at?
No it will not group your records.
Try Message.where("sender_id IN (?) AND receiver_id IN (?)", @ids, @ids).group("sender_id,receiver_id").order("created_at ASC")
Thanks I tried that but it errors with column "messages.id" must appear in the GROUP BY clause or be used in an aggregate function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.