Rails active record, how can I request a HABTM relationship

I have a model 2 that has a HABTM ratio

User

has_and_belongs_to_many :rooms

Room

has_and_belongs_to_many :users

I also create a transition to join a 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 request a room in which user_id of user B is among the rooms of user A. How can I do this?

+4
source share
2 answers

I'm not sure that you can do this in a single SQL call, but it looks like you want to combine the two sets.

UserA.rooms & UserB.rooms

This should give you the rooms of both users.

+1
source

it 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})
0
source

Source: https://habr.com/ru/post/1695121/


All Articles