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
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
In the meantime I have created a Rails plugin based on my idea above, but with a more improved algorithm. Check it out here:
http://github.com/ledermann/unread