Reputation: 43
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?
Upvotes: 4
Views: 786
Reputation: 3586
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.
Upvotes: 2
Reputation: 11216
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})
Upvotes: 0