AlexNikolaev94 AlexNikolaev94 - 7 months ago 12
Ruby Question

last_online attribute of user remains `nil`

I'm building a small real-time chat and I'm stuck with listing the users online. I have a custom

User
model, and in way to list the list online users out I made a migration
add_last_online_to_users last_online:datetime
. Then, in my
user.rb
:

def self.online_now
where("last_online > ?", 15.minutes.ago)
end


in
application_controller.rb
:

def show_online
@users = User.online_now
end


in
sessions_controller.rb
:

def create
user = User.from_omniauth(request.env["omniauth.auth"])
cookies[:user_id] = user.id
user.last_online = Time.now
end


in
messages_controller.rb
:

def create
respond_to do |format|
if current_user
@message = current_user.messages.build(message_params)
@message.save
current_user.last_online = Time.now
format.html{redirect_to root_path}
format.js
else
format.html{redirect_to root_path}
format.js {render nothing: true}
end
end
end


and finally the view:

<ul>
<%= @users.each do |user| %>
<li><%= user.name %></li>
<% end %>
</ul>


But when I check after signing in or sending a message in console -
User
's
last_online
is
nil

Answer

It seems that you are not saving last_online attribute in sessions_controller.rb, just assigning the value. Instead try this:

def create
    user = User.from_omniauth(request.env["omniauth.auth"])
    cookies[:user_id] = user.id
    user.update_attributes(last_online: Time.now)
end

Same thing in messages_controller.rb. Try replacing current_user.last_online = Time.now with current_user.update_attributes(last_online: Time.now)

Comments