4

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

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

但它给了我两个用户之一所在的所有聊天。

我也试过:

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

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

编辑:

我的聊天模型:

class Chat < ActiveRecord::Base
  has_and_belongs_to_many :users
  scope :of_users, ->(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"
4

2 回答 2

1

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

于 2013-09-19T09:17:08.200 回答
1

使用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 ") }
于 2013-09-19T09:22:18.430 回答