How to find out if something has been read in Rails for notification

I would like to implement a simple notification system on my website, on which the user will display an invisible / unread item. Similar to the one used by Stack Exchange for the user's mailbox, where unread comments on questions, etc. are displayed.

I came across this question , which provides an overview of how I will do this. What confuses me is how to find out if something has been read. I could add a read_at column, but how to fill it? If anyone could help me with some basic instructions, I would appreciate it!

UPDATE # 1: What if I add a condition to my Item # show action, where I check user_id (the ID of the user creating the item), on current_user.id . Something like below:

 unless @item.user_id == current_user.id @item.read_at = Time.now end 

UPDATE # 2: Using the code below, I am trying to update the read_at message if its recipient_id matches the current_user id. However, it does not work.

 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 @prasvin, here is my solution. I added a read_at column to the object. The object also has an existing recipient_id column. So, in my show Controller action, I set 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 %> 
+6
source share
1 answer

How about populating the read_at column in the show action, i.e. we have the object in the show action, and then update its read_at attribute before we pack the page

+2
source

Source: https://habr.com/ru/post/907815/


All Articles