1

In this question I asked how to list out users currently online in the chat. While discussing I was given an answer, and I tried to implement it, but I didn't succeed. So, I made a migration add_last_online_to_users last_online:datetime and made a tweak in User model:

user.rb:

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

And then added to my Message controller, so that each time an user sends a message, his last_online updates to Time.now. Finally, I added to my application_controller the following code:

def show_online
  @users = User.online_now
end

and called that method in my view:

<% @users.each do |user| %>
    <%= user.show_online %>
<% end %>

that returned me a NoMethodError: undefined method 'each' for nil:NilClass

Community
  • 1
  • 1
AlexNikolaev94
  • 1,169
  • 2
  • 16
  • 40

2 Answers2

3

But it returned me an error that online_now column doesn't exist in database

You cannot query with a method, so @users = User.where(online_now: true) won't work. Instead you have to do like below

def show_online
  @users = User.online_now
end
Pavan
  • 33,316
  • 7
  • 50
  • 76
0

No problem with your codes. I think your view and your controller/action are different. It mean you try show @users to another view not "show_online.html.erb"

You just have a syntax error in your model

where ("last_online > ?", 15.minutes.ago)

should be

where("last_online > ?", 15.minutes.ago)
thanhnha1103
  • 1,037
  • 1
  • 8
  • 18