Rails: read / unread message management

for a forum-like application, I need the ability to show each user unread (new) messages. Is there any Rails plugin / gem for this?

Or: Are there any hints to make this work in an efficient way? I am thinking of an additional database table storing the unread status (or read status?) Of each message for each user. But this seems like brute force, maybe there is a more reasonable solution ...

Best regards, Georg

+2
source share
2 answers

, . . , . , , "" .

:

# Get number of unread posts of the logged-in user:
Discussion.unread_by(current_user).count
# => 42

# Mark a topic as read
some_topic = Discussion.find(x)
some_topic.read_by!(current_user)

"ReadStatus":

class ReadStatus < ActiveRecord::Base
  belongs_to :user
  belongs_to :discussion

  validates_presence_of :user_id, :discussion_id, :post_count
end

"" :

class Discussion < ActiveRecord::Base
  belongs_to :user
  belongs_to :topic, :class_name => 'Discussion', :foreign_key => 'discussion_id'

  named_scope :unread_by, lambda { |user| 
      { :joins => "LEFT JOIN read_statuses ON (read_statuses.user_id = #{user} AND 
                                               read_statuses.discussion_id = discussions.id)",
        :conditions => "discussions.discussion_id IS NULL
                        AND (read_statuses.user_id IS NULL) OR (read_statuses.post_count < discussions.post_count)",
        :order => 'discussions.updated_at DESC' 
      }
  }


  def read_by!(user)
    if read_status = ReadStatus.first(:conditions => { :user_id => user.id, :discussion_id => self.id })
      read_status.update_attributes! :post_count => self.post_count
    else
      ReadStatus.create! :user_id => user.id, :discussion_id => self.id, :post_count => self.post_count
    end
  end
end
+6

Source: https://habr.com/ru/post/1776962/


All Articles