我们有一个Conversation
和一个User
模型。有一个联接表ConversationsUser
。一个convo只能有两个用户。我想创建一种方法,该方法将返回现有对话,或创建一个新对话。
给定两个User
,我想做一个查询,例如:查找两个ConversationsUser
相等的两个conversation_id
记录,并且user_id
是{{ 1}}和user1
。
如何构造该查询?
答案 0 :(得分:0)
可以在对话的两个用户之间使用唯一列(key: text
)进行维护,也可能有简单的解决方案,
class Conversation < ApplicationRecord
# Associations
has_many :conversation_users, dependent: :destroy
has_many :users, through: :conversation_users
# Validations
#add key:text in conversations table
validates :key, uniqueness: {case_sensitive: false}, :allow_blank => true
# Callbacks
before_validation :update_key
def update_key
self.key = Conversation.key_for_users(self.users)
end
# method that will return an existing conversation, or create a new one.
def self.between(users)
key = self.key_for_users(users)
conversation = Conversation.where(key: key).first_or_create
conversation.users = users
conversation.save
return conversation
end
end
=>这样的查询:查找两个ConversationsUser记录,两个记录的session_ids相等,并且user_id为user1和user2。
conversation = Conversation.between([user1, user2])