Rails finds an entry with all association identifier matches

I have a HABTM connection between users and chats. I am trying to find Chat with two specific users. I tried:

scope :of_users, ->(user1,user2) { joins(:users).where( users: { id: [ user1.id, user2.id ] } ) } Chat.of_users( user1, user2 ) 

But he gives me all the chats in which one of the two users is located.

I also tried:

 Chat.joins(:users) & User.where(id:1) & User.where(id:2) 

He did not give me the correct results. What am I looking for? I searched everywhere but I don’t know the name of this concept ...

EDIT:

My chat model:

 class Chat < ActiveRecord::Base has_and_belongs_to_many :users scope :of_users, ->(user1,user2) { joins(:users).where( users: { id: [ user1.id, user2.id ] } ) } end 

My user model:

 class User < ActiveRecord::Base has_and_belongs_to_many :chats end 

Scheme for user and chat:

 create_table "chats", :force => true do |t| t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "chats_users", :id => false, :force => true do |t| t.integer "chat_id" t.integer "user_id" end add_index "chats_users", ["chat_id", "user_id"], :name => "index_chats_users_on_chat_id_and_user_id" add_index "chats_users", ["user_id"], :name => "index_chats_users_on_user_id" 
+4
source share
2 answers

user1.chats & user2.chats according to the correct HABTM for your user model

+1
source

Use the having to check if both users are in related users.

 scope :of_users, ->(user1,user2) { joins(:users).group("chats.id") # the condition within SUM returns 1 if both users present else 0 .having("SUM(users.id = #{user1.id} AND users.id = #{user2.id}) > 0 ") } 
+1
source

All Articles