4

I have 2 Model which have HABTM relation

User

has_and_belongs_to_many :rooms

Room

has_and_belongs_to_many :users

I also create the migration to join the table like this

create_join_table :users, :rooms do |t|
      t.index [:user_id, :room_id]
      t.index [:room_id, :user_id]
end

I would like to query the room which is contained user_id of user B in among of user A's rooms. How can I do it?

Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
MindaRyn _
  • 43
  • 2

2 Answers2

2

I’m not sure you can do this in a single SQL call but it sounds like you want the union of two sets.

UserA.rooms & UserB.rooms

That should give you the rooms both users shared.

danielricecodes
  • 3,446
  • 21
  • 23
0

this should work

user_b = User.find(id: 123) #or id of user b
user_a = User.find(id: 234) #or id of user a

user_b.rooms.joins(:users).where(users: {id: user_a.id})
lacostenycoder
  • 10,623
  • 4
  • 31
  • 48