ruby-on-rails - 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]}%")
但它不起作用。如何实施?
解决方案
我不确定你的模型 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)
顺便说一句,我建议你寻找另一种方法。
推荐阅读
- ios - iOS - NSISEngine 崩溃
- json - 如何从 JSON 文件中获取特定数据?
- android - 带有 Gridlayoutmanager 的 Recyclerview 的 Android Firebase 分页
- javascript - 无法使用 Google Apps 脚本发送带附件的电子邮件
- python - numpy .dot 使用列表和数组,有什么区别
- python - 从 32 位 python 运行 64 位 powershell
- c - 无法执行找到与给定字符匹配的字符串的第一个字符的代码
- python - 采用两个 ShortUUID 并输出一致唯一的字符串以进行标识的函数
- javascript - 从本地文件系统提供的 Webworker 无法正常工作
- html - 我的建议 div 落后于另一个 div