Monday, September 21, 2009

Showing unread posts/comments: An example of rails ActiveRecord 'touch'

I worked on the following story:-
"As a partner, when I visit a project's dashboard I want to see five most recently started or updated discussion threads with number of unread comments, if any. If any of these are new, I want to see them in a highlighted view. Next, if I open the thread, I want to see all new comments in a highlighted view as well. However, once seen, the threads/comments should no longer be highlighted from the rest."
I used the following steps to implement this.

Step#1: Added a model MessageReadTime (message_id, user_id, last_read_at)
class Message 
has_many :messages_read_times 
end
Step#2: Added filters in the messages_controller
after_filter :update_message_read_time, :only => [:show]
def update_message_read_time
read_time = MessageReadTime.find_or_create_by_message_id_and_user_id( params[:id], current_user.id)
read_time.last_read_at = Time.now
read_time.save!
end
Step#3: Added :touch=>true and unread? function in Comment class
class Comment
..
belongs_to :message, :touch => true
def unread?(user)
read_time = self.message.message_read_times.find_by_user_id(user_id)
return true unless(read_time)
return read_time.last_read_at < (updated_at || created_at) end end
Step#4: Added unread_comments method in Message class like this
class Message
...
def unread_comments(user)
self.comments.collect{|comment| comment.unread?(user) ? comment : nil }.compact
end

def unread?(user)
read_time = self.message_read_times.find_by_user_id(user.id)
return true unless read_time
return self.updated_at >= read_time.last_read_at
end
...
end
This is it! If you know a better way to do this, lets discuss in the comments. You are also welcome to share your thoughts/suggestions :-)