Search code examples
ruby-on-railsactiverecordhas-and-belongs-to-many

Rails active record, how can I query in HABTM relation


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?


Solution

  • 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.