Rails,通过关联找到

时间:2016-01-25 14:11:35

标签: ruby-on-rails relationships

我即将为rails应用程序构建消息传递功能。

我考虑过conversationsconversation_participantsconversation_messages

这意味着:

会话:

has_many :conversation_participants
has_many :conversation_messages, through: :conversation_participants

对话参与者:

belongs_to :conversation
belongs_to :user
has_many :conversation_messages

会话消息:

belongs_to :conversation_participant

到目前为止,非常好。

我只是陷入了某些情况:

  • 如何找到用户1和用户2的对话?
  • 如何找到用户1,用户4和用户1的用户。用户5?
  • 如果有两个对话怎么办,一个是针对用户1,4,5,另一个是针对1,4,5,6,但我只是在寻找1,4,5?

希望有人可以帮我解决这个问题!谢谢!

3 个答案:

答案 0 :(得分:1)

您可以排除converstion_messages。这些都是无关紧要的,需要包括用户。

System.IO.FileStream

现在,您可以选择仅包含1,2和3的对话(作为user_ids)

#user 
has_many :conversations, through: converstion_participants

user_12_conv_ids = user_1.conversation_ids & user_2.conversation_ids
user_123_conv_ids = user_12_conv_ids & user_3.conversation_ids

user_123_conversations = Conversation.where(id: user_123_conv_ids) 

答案 1 :(得分:1)

您可能希望更多地了解mergewhere方法。

第一个例子看起来像:

Conversation.joins(:conversation_participants).merge(User.where(:id => user1_id)).merge(User.where(:id => user2_id))

每个merge()都会过滤结果。您不希望使用merge(User.where(:id => [user1_id, user2_id])),因为您将获得两个用户的所有对话,而不仅仅是普通用户。

第二个例子与第一个例子类似。

在第三个示例中,您可以在查询末尾添加.merge(User.where.not(:id => user6_id)之类的内容,以便不包含与用户6的对话。

<强>更新

要动态链接多个merge,您可以尝试以下内容:

conversations = Conversation.joins(:conversation_participants)
user_ids.each{|uid| conversations.merge!(User.where(:id => uid))}

答案 2 :(得分:0)

听起来您会希望通过对话参与者在用户和对话之间建立关联。

  

如何找到用户1和用户2的对话?

根据您设置的方式,这似乎不是一个独特的对话。用户1和2可以仅与彼此进行一次对话,而另一次对话则包括其他参与者。话虽这么说,如果你在conversation_id上加入conversation_participants表,你应该能够找到匹配项。还有其他方法可以解决这个问题,我很乐意提供更多信息。您决定接近此问题的方式也将考虑到您的其他问题的答案。

更新:

查询看起来像这样:

SELECT cp1.conversation_id 
FROM conversation_participants as cp1 
JOIN conversation_participants as cp2 ON cp1.conversation_id = cp2.conversation_id 
WHERE cp1.participant_id = 1 and cp2.participant_id =2;