导轨发现记录与所有关联的ID匹配 [英] Rails find record with all association ids matching
本文介绍了导轨发现记录与所有关联的ID匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有用户和聊天之间的HABTM关联。我试图找到它2特定的用户聊天。我想:
范围:of_users, - >(用户1,用户2){联接(:用户)。凡(网友:{ID:[user1.id,user2.id]})}
Chat.of_users(用户1,用户2)
但它给了我所有的聊天,其中两个用户之一是
我也试过:
Chat.joins(:用户)及User.where(ID:1)及User.where(ID:2)
没给我正确的结果无论是。我是什么找?我一直在寻找所有的地方,但我不知道这个概念的名字......
编辑:
我的聊天模式:
类聊天< ActiveRecord的::基地
has_and_belongs_to_many:用户
适用范围:of_users, - >(用户1,用户2){联接(:用户)。凡(网友:{ID:[user1.id,user2.id]})}
结束
我的用户模型:
类用户< ActiveRecord的::基地
has_and_belongs_to_many:聊天
结束
模式对于用户和聊天:
CREATE_TABLE聊天:力=>真正做| T |
t.datetimecreated_at:空=>假
t.datetime的updated_at:空=>假
结束CREATE_TABLEchats_users:ID =>假:力=>真正做| T |
t.integerchat_id
t.integerUSER_ID
结束add_indexchats_users,[chat_id,USER_ID]:名称=> index_chats_users_on_chat_id_and_user_id
add_indexchats_users,[user_ID的]:名称=> index_chats_users_on_user_id
解决方案
user1.chats&安培; user2.chats
按正确的HABTM你的用户模型
I have a HABTM association between Users and Chats. I'm trying to find the Chat with 2 specific users in it. I tried:
scope :of_users, ->(user1,user2) { joins(:users).where( users: { id: [ user1.id, user2.id ] } ) }
Chat.of_users( user1, user2 )
But it gives me all Chats where one of the two Users is in.
I also tried:
Chat.joins(:users) & User.where(id:1) & User.where(id:2)
Didn't give me the right results either. What am I looking for? I've been searching all over the place, but I don't know the name of this concept...
EDIT:
My Chat model:
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
My User model:
class User < ActiveRecord::Base
has_and_belongs_to_many :chats
end
Schema for User and Chat:
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
as per correct HABTM on you user model
这篇关于导轨发现记录与所有关联的ID匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文