Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Management of read/unread messages

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

Or: Are there any hints to do this job in a efficent way? I'm thinking about an additional database-table storing the unread-status (or read-status?) of every message for every user. But this seems to be brute-force method, perhaps there is a smarter solution...

Best wishes, Georg

like image 481
Georg Ledermann Avatar asked Nov 30 '22 06:11

Georg Ledermann


1 Answers

To whom it may concern, here is my solution. I have added a new table for storing the read status. A row in this table gives the number of posts a user has read so far in a given topic. If a topic has more posts then the user has read, it's called an "unread" topic.

Usage:

# 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)

Simple model "ReadStatus":

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

  validates_presence_of :user_id, :discussion_id, :post_count
end

Extract from model "Discussion" for storing topics and posts:

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
like image 85
Georg Ledermann Avatar answered Dec 26 '22 04:12

Georg Ledermann