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"
source share