Tim Baas
Tim Baas

Reputation: 6185

Rails find record with all association ids matching

I have a HABTM association between Users and Chats. I'm trying to find the Chat with 2 specific users in it. I tried:

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

But it gives me all Chats where one of the two Users is in.

I also tried:

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

Didn't give me the right results either. What am I looking for? I've been searching all over the place, 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

Schema 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"

Upvotes: 4

Views: 1483

Answers (2)

tihom
tihom

Reputation: 8003

Use having clause to check presence of both users in the associated 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 ") }

Upvotes: 1

Rajarshi Das
Rajarshi Das

Reputation: 12320

user1.chats & user2.chats as per correct HABTM on you user model

Upvotes: 1

Related Questions