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

时间:2013-09-19 08:32:57

标签: ruby-on-rails join associations

我在用户和聊天之间有一个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 < 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"

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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 ") }
相关问题