【问题标题】:Scope records which don't have an associated record没有关联记录的范围记录
【发布时间】:2022-12-18 11:41:42
【问题描述】:

我的应用程序中有聊天功能。当 Chat::Message::Interaction 为该消息和该用户退出时,Chat::Messages 被用户“读取”。

当用户打开聊天时,我想在后台作业中将所有未读消息标记为已读。我正在通过 chat.message.unread(user) 查找未读消息。这使用消息模型上的 unread 范围从数据库中提取每条聊天消息。

有没有更好的方法来获取与特定用户没有交互的聊天的所有消息?

class Chat::Message::Interaction < ApplicationRecord
  belongs_to :user
  belongs_to :message
  delegate :chat, to: :message

  validates :user, uniqueness: { scope: :message }
end
class Chat::Message < ApplicationRecord
  belongs_to :user
  belongs_to :chat
  has_many :interactions, dependent: :destroy
  has_noticed_notifications

  default_scope { includes(:user) }

  scope :unread, ->(user) { where.not(id: Chat::Message::Interaction.where(user:).pluck(:message_id)) }

  def read?(user)
    interactions.find_by(user:).present?
  end

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    您的范围可能会产生 ... WHERE message_id NOT IN &lt;potentially huge list of ids&gt; 查询 - 我宁愿不惜一切代价避免这种情况(更不用说对交互的额外查询)。

    如果您需要选择没有关联实体的实体,则有一种(通常)性能更高的方法 - 左外连接。像下面这样的东西通常应该更好用:

    scope :unread, -> { left_joins(:interactions).where(interactions: { id: nil }) }
    
    

    (加上它“更可重用”,因为它没有耦合到特定用户)

    【讨论】:

      猜你喜欢
      • 2022-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 2016-08-12
      • 1970-01-01
      相关资源
      最近更新 更多