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?
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.
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})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.