Scope records which don't have an associated record
I have a chat function in my app. Chat::Messages
are "read" by a user when an Chat::Message::Interaction
exits for that message and that user.
When a user opens the chat, I want to mark all unread messages as read in a background job. I'm finding the unread messages by doing chat.message.unread(user)
. This uses the unread
scope on the message model pulls every chat message from the database.
Is there a better way of getting all messages for a chats which don't have an interaction for a specific user?
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
精彩评论