ledermann / unread

Handle unread records and mark them as read with Ruby on Rails
MIT License
739 stars 121 forks source link

Get list of records that have unread related records. #87

Closed leadingproperties closed 7 years ago

leadingproperties commented 7 years ago

I have Conversation that has_many Messages. Is there best way to get Conversations with unread messages inside?

class Conversation < ApplicationRecord
  has_many :messages
end

class Message < ApplicationRecord
  acts_as_readable :on => :created_at
  belongs_to :conversation
end

After few hours of try's, and after I wrote this question (order thoughts) - my solution is:

user = User.last
Conversation.joins(:messages).where(id: Message.unread_by(user).pluck(:conversation_id))

Think this query will return Conversations with unread messages inside. May be there is the better way?

ledermann commented 7 years ago

What about this:

class Conversation < ApplicationRecord
  has_many :messages
  acts_as_readable_on on: :updated_at
end

class Message < ApplicationRecord
  belongs_to :conversation, touch: true
  acts_as_readable :on => :created_at
end

Conversion.unread_by(user)
leadingproperties commented 7 years ago

Thank's for quick response. You are opened my eyes with this simple solution. I review my design and notice that I don't need mark read messages at all. I can mark Conversations. Thanks!