I’d like to implement a simple notification system on my site where an unseen/unread item is displayed to the user. Similar to the one used across Stack Exchange for the user’s inbox where unread comments on questions, etc are displayed.
I came across this question that provides an overview of how I’d do this. What I’m confused about is how to figure out if something has been read. I could add a read_at column but how do I actually fill it? If anyone could help me with some basic guidance I’d appreciate it!
UPDATE #1: What if I add a conditional to my Item#show action where I check the user_id (ID of the user creating the item) against current_user.id. Something like the below:
unless @item.user_id == current_user.id
@item.read_at = Time.now
end
UPDATE #2: Using the code below, I’m attempting to update the message’s read_at if its recipient_id matches the current_user ID. However it’s not working.
def show
@message = Message.find(params[:id])
if @message.recipient_id == current_user.id
@message.read_at == Time.now
@message.save
end
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @message }
end
end
FINAL UPDATE: Thanks to @prasvin, here’s my solution. I added a read_at column to the object. The object also has an existing recipient_id column. So in my Controller’s show action, I put the following:
def show
@message = Message.find(params[:id])
if @message.recipient_id == current_user.id
@message.update_attributes(:read_at => Time.now)
end
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @message }
end
end
Then in my helper.rb file:
def new_messages
Message.where(:recipient_id => current_user.id, :read_at => nil).count
end
And in my layout:
<% if new_messages > 0 %><span class="notification"><%= new_messages %></span><% end %>
How about filling in
read_atcolumn in show action, i.e. we have the object in the show action,and then update its read_at attribute before redering the page