【发布时间】:2019-10-07 14:26:43
【问题描述】:
我有一个用户模型和一个对话模型。 User 有很多对话,Conversation 有很多用户,所以我通过连接表 :conversations_users 使用 has_and_belongs_to_many 关系。我使用该方法返回特定用户之间的对话(按用户 ID):
def find_conversation_between_users(ids)
conversation = nil
conversations = Conversation.all
if conversations.present?
conversations.each do |conv|
next unless conv.user_ids == ids.sort
conversation = conv
end
end
end
class Conversation < ApplicationRecord
has_and_belongs_to_many :users
end
class User < ApplicationRecord
has_and_belongs_to_many :conversations
end
它可以工作,但如果我们有数千个对话并且迭代每个对话将花费太多时间,它就不会有效。 所以我尝试通过相关的 user_ids [1 , 2, 3] 创建返回特定对话的范围。
scope :by_user_id, ->(user_ids) { joins(:conversations_users).where([ conversations_users: { user_id: user_ids } ]) }
但它不起作用。
【问题讨论】:
-
你准备好换成
has_many: through了吗?如果是的话,我想我可以给你解决方案。基本上表没有变化——只需要创建ConversationsUser模型。
标签: ruby-on-rails activerecord scope has-and-belongs-to-many