0

I have has_and_belongs_to_many association between two models Chat and User.

I need to search for a chats by chat_members (user_ids).

for example:

Chat.where(users: User.last(3))

Is there an easy way to implement this task?

  • 1
    `Chat.joins(:users).where(users: { id: ids_array })` – Marek Lipka Mar 23 '20 at 13:13
  • @MarekLipka it returns all chats for given user ids. My aim to return chat, which includes exact users. – Kirill Berlin Mar 23 '20 at 16:04
  • I don't think this will be possible in pure AR, you would need to mix in some SQL as well. I am not sure if that works for you. If it does, do mention if you are using a RDBMS like Postgres or MySQL. – erosenin Mar 25 '20 at 11:26
  • @erosenin I'm using postgres and if you know raw SQL query which can cover my issue - it will be great! – Kirill Berlin Mar 26 '20 at 12:04
  • @KirillBerlin I am going to assume your association table is called `chat_users`. Also, the chats should have exactly the users in user_ids or at least the users in user_ids? – erosenin Mar 26 '20 at 19:17
  • @erosenin I has relation similar to this post. 3 tables, one of it contains ids of two others chat_id and user_id – Kirill Berlin Mar 27 '20 at 23:09

0 Answers0