One quite important feature of this site is a list of members who are currently online. First off this only works if you use ActiveRecord to manage your sessions. To do this you must uncomment the following line in your environment.rb file:
config.action_controller.session_store = :active_record_store
.
Then create the sessions table by running the following command from your RAILS_ROOT:
rake db:sessions:create
.
Now, whenever a user logs in to your application add their id to the session. In my app at the moment it looks something like this:
member = Member.new( @params[ :member ] )
member = Member.find( :all, :conditions => "screen_name = '#{member.screen_name}' AND password = '#{member.password}'" )
if member != nil
session[ :member_id ] = member.id
redirect_to :action => 'success'
else
redirect_to :action => 'form'
end
Now to find all of the users who are currently online it is just a matter of searching the sessions table for all the users who have been active in the last 10 minutes. This can be done using rails built in session model. Finally the session data needs to be unmarshaled and decoded. This stumped me for a while, but finally I found the answer at http://caboo.se/doc/classes/CGI/Session/ActiveRecordStore/SqlBypass.html. So here is my code to return an array of the member_ids of all the members online and active within the last 10 minutes.
def who_is_online
@whos_online = Array.new()
onlines = CGI::Session::ActiveRecordStore::Session.find( :all, :conditions => [ 'updated_at = ?', Time.now() - 10.minutes ] )
onlines.each do |online|
id = Marshal.load( Base64.decode64( online.data ) )
@whos_online << id
Have Nice Try and Good Luck