I bring to mind a little chat, who wrote, and faced the following difficulty - I wanted to deduce users that they are online in a chat, but it doesn’t work. In order to define a user online, I first created a migration in the database and added the last_online attribute: add_last_online_to_users last_online:datetime to the user model. Then I added the online_now method to the User class:
class User < ActiveRecord::Base has_many :messages, dependent: :delete_all class << self def from_omniauth(auth) provider = auth.provider uid = auth.uid info = auth.info.symbolize_keys! user = User.find_or_initialize_by(uid: uid, provider: provider) user.name = info.name user.avatar_url = info.image user.profile_url = info.urls.send(provider.capitalize.to_sym) user.save! user end def online_now where("last_online > ?", 15.minutes.ago) end end end and in application_controller.rb :
def show_online @users = User.online_now end Also, in the controllers that are responsible for creating a new session and sending a message, I specified the condition for updating the last_online attribute
messages_controller.rb :
def create respond_to do |format| if current_user @message = current_user.messages.build(message_params) @message.save current_user.update_attributes(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 sessions_controller.rb
def create user = User.from_omniauth(request.env["omniauth.auth"]) cookies[:user_id] = user.id user.update_attributes(last_online: Time.now) end and finally in the view:
<ul> <%= @users.each do |user| %> <li><%= user.name %></li> <% end %> </ul> Checked through the User.online_now console - the user that is currently logged in to the chat or sent a message is there, but not in the list.
pry, see that in@usersand that inUser.online_now. - D-sideuser.update_attributes(last_online: Time.now)but does this work out at all? Maybe there is an invalid user. In the database, if you look at what is in this field for an authorized user? 2.show_onlineand where is it called at all? - anoamlast_onlineattribute. 2.show_onlineis called in a common view through@users.each- AlexNikolaev94