I’m going through Michael Hartl’s Railstutorial and I am stuck on Exercise 9.6.2. I searched online and used this code in my Sessions Helper:
module SessionsHelper
def sign_in(user)
session[:user_id] = user.id
self.current_user = user
end
def current_user=(user)
@current_user = user
end
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def signed_in?
!current_user.nil?
end
def sign_out
session[:user_id] = nil
self.current_user = nil
end
end
I found it online from: http://www.nimweb.it/web-development/ruby-on-rails-web-development/ruby-on-rails-tutorial-exercise-9-6-2-rails-session/
However, the user is not logged out when the browser is closed. Does anyone else have a solution to this?
EDIT:
Looking at the link you gave, they write:
(emphasis added)
Therefore, their solution is to simply turn off cookies, which results in a new session being created with each visit. They are not really talking about removing old sessions on the server side of the equation.
My original answer is left below for historical value:
(apologies if this is too general, I’m assuming you’re not seeing the bigger picture)
Fundamentally, the web uses a pull-based model – clients make requests to do things on the server.
You can not ‘force’ the client to close a session, since closing a session is an action that the client must request from the server (eg: by logging out).
Therefore, typically sessions have a time-out period that is checked regularly. Each session has a ‘start time’ stored in the database, and sessions that are too old are purged.
That said, there may be some way in javascript to detect a browser close event and make some best-effort attempt to close the session. But there is no guarantee – the user can always forcefully kill the browser process, leaving the server totally in the dark.
In short, you can’t rely on the client to close a session. A timeout is probably your best option.