Q:

Rails and Authlogic. Show currently logged in users

I would like to have the list of currently logged in users.
This code doesn't work :
<% UserSession.all.each do |user_session| %>

<% end %>

A:

@syed-aslam has a good solution, but you could just let Authlogic do the work. Check out the module Authlogic::ActsAsAuthentic::LoggedInStatus which defines two scopes: logged_in, logged_out
Your code becomes:
<% User.logged_in.each do |user| %>

<% end %>

P.S. I would normally link to the RDoc instead of source code, but the RDoc seems to have problems at the moment.

A:

Authlogic gives you all kind of automatic columns that you don’t really need to update or maintain on your own, they are maintained by the actual code flow of Authlogic itself.
Those fields can contain some basic functionality related issues like the number of login attempts made, the ip address from which the attempt was made an or even what was the ip address the last time that user logged in. fun.
The magic column that will help us find who is probably online is the one called last_request_on, which basically indicates when was the last time that user made a request to your application.
The second parameter we’ll need in order to make a more accurate selection, is the configuration option named logged_in_timeout, which sets the timeout after which a stale session will be expired, by default it will expire after 10 minutes.
so if you set your session expiry to 30 minutes:
class User << ActiveRecord::Base
  acts_as_authentic do |c|
    c.logged_in_timeout 30.minutes
  end
end

searching for those users is pretty easy:
module OnlineUsers
  def count_online_users
    User.count(:conditions => ["last_request_at > ?", 30.minutes.ago])
  end
end

