首页 > 解决方案 > Rails - 如何搜索有很多关系

问题描述

我有 3 个模型 - User、Conversation 和 UserConversation

class Conversation < ApplicationRecord
  has_many :messages,  -> { order 'created_at' }, dependent: :destroy
  has_many :user_conversations, dependent: :destroy
  #if conversation is destroyed all messages and subscriptions will also be  destroyed
  has_many :users, through: :user_conversations
end
class User < ApplicationRecord
    has_many :sent_messages, 
           class_name: 'Message', 
           foreign_key: 'sender_id' 
    has_many :messages, foreign_key: 'recipient_id'

    has_many :user_conversations, dependent: :destroy
    has_many :conversations, through: :user_conversations

end
class UserConversation < ApplicationRecord
  belongs_to :user
  belongs_to :conversation

  validates_presence_of :user_id, scope: :conversation_id
end

我想搜索当前用户的对话,并且只找到其他用户名称喜欢某些值的对话。

conversations = @current_user.conversations
conversations = conversations.users.where("name ILIKE ?", "%#{params[:search]}%")

但它不起作用。如何实施?

标签: ruby-on-rails

解决方案


我不确定你的模型 Conversation 是抽象还是真的假装是聊天,但是如果你想找到 current_user 与另一个用户的所有对话,你需要你的 Conversation 模型与两个用户都有关系,但是方式您的关系工作令人困惑,请尝试:

class User < ApplicationRecord
  # all your previous code

  def find_conversations_by(user_name)
    self.conversations.joins(:user).where("user.name ILIKE ?", "%#{user_name}%") 
  end
end

现在,无论您想在哪里使用它,都可以这样写:

current_user.find_conversations_by(a_proof_query_injection_string)

顺便说一句,我建议你寻找另一种方法。


推荐阅读