问题
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
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/2290496/rails-management-of-read-unread-messages