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
  • I tried your answer and in returns me `undefined method 'each' for nil:NilClass`. I've updated my question with a piece of code that makes the issue – AlexNikolaev94 Apr 16 '16 at 12:30
  • @AlexNikolaev94 That means there are no records matching that condition. – Pavan Apr 16 '16 at 12:31
  • because there's no users? – AlexNikolaev94 Apr 16 '16 at 12:32
  • @AlexNikolaev94 Yes there are no records matching that condition. – Pavan Apr 16 '16 at 12:34
  • so if I want the chat to work even if there's no users online, should I put that in something like `if @users.any?` – AlexNikolaev94 Apr 16 '16 at 12:40
  • @AlexNikolaev94 Put that in `if !@users.blank?` – Pavan Apr 16 '16 at 12:45
  • so that helped but there's another problem that I checked via console - although I added to my sessions and messages controller that when user sends message his `last_online` updates to `Time.now`, my column `last_online` of the user remains `nil` – AlexNikolaev94 Apr 16 '16 at 18:31
  • @AlexNikolaev94 Please ask another question explaining your problem detail. As of now accept my answer as it solved your current problem :) – Pavan Apr 16 '16 at 18:32
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