Rails找到所有关联ID匹配的记录

我在用户和聊天之间有一个HABTM关联。 我正在尝试在其中找到包含2个特定用户的聊天。 我试过了:

scope :of_users, ->(user1,user2) { joins(:users).where( users: { id: [ user1.id, user2.id ] } ) } Chat.of_users( user1, user2 ) 

但是它给了我所有Chats,其中有两个用户中的一个。

我也尝试过:

 Chat.joins(:users) & User.where(id:1) & User.where(id:2) 

没有给我正确的结果。 我在找什么? 我一直在寻找各地,但我不知道这个概念的名称……

编辑:

我的聊天模型:

 class Chat (user1,user2) { joins(:users).where( users: { id: [ user1.id, user2.id ] } ) } end 

我的用户型号:

 class User < ActiveRecord::Base has_and_belongs_to_many :chats end 

用户和聊天的架构:

 create_table "chats", :force => true do |t| t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "chats_users", :id => false, :force => true do |t| t.integer "chat_id" t.integer "user_id" end add_index "chats_users", ["chat_id", "user_id"], :name => "index_chats_users_on_chat_id_and_user_id" add_index "chats_users", ["user_id"], :name => "index_chats_users_on_user_id" 

user1.chats & user2.chats根据您的用户模型上的正确user1.chats & user2.chats

使用having子句检查关联用户中两个用户的存在

 scope :of_users, ->(user1,user2) { joins(:users).group("chats.id") # the condition within SUM returns 1 if both users present else 0 .having("SUM(users.id = #{user1.id} AND users.id = #{user2.id}) > 0 ") }