gpt4 book ai didi

ruby-on-rails - Rails 查找所有关联 ID 匹配的记录

转载 作者:行者123 更新时间:2023-12-01 03:54:05 25 4
gpt4 key购买 nike

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

最佳答案

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

关于ruby-on-rails - Rails 查找所有关联 ID 匹配的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18889824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com