NOTE: This information is mostly outdated

By default, acts_as_authenticated only stores the user ID in the session. While this ensures that the session is never stale, it does require a database query every time you need the current_user info. An alternative to this is storing the current user’s object in the session .

Of course, doing this will give you session staleness…

Middle ground, or how to compromise

Next I will describe how to walk the middle ground. This is by no means perfect, but it does give a nice compromise for some situations.

Add the following code to your app/controllers/application.rb file:

# Returns true or false if the user is logged in.
def logged_in?
# Accesses the current user from the session. 
def current_user
  if logged_in?
    # update session if it is older then 10 minutes
    if (session[:user_fresh] + 10.minutes) <=
      current_user = User.find(session[:user].id)

# Store the given user in the session.
def current_user=(new_user)
  session[:user] = new_user.nil? ? nil : new_user
  session[:user_fresh] = new_user.nil? ? nil :
  @current_user = new_user

This will refresh the session if the data is older then 10 minutes. As such, your session’s won’t become very stale. If 10 minutes isn’t to your liking, feel free to change the value :)

What is staleness defines ‘stale’ as:

Stale \Stale\, a. [Akin to stale urine, and to stall, n.; probably from Low German or Scandinavian. Cf. Stale, v. i.]

  1. Not new; not freshly made; as, stale bread.

Stale \Stale\, n. [See Stale, a. & v. i.]

  1. That which is stale or worn out by long keeping, or by use. [Obs.]

The word ‘stale’ in programming refers to something that is no longer current, or holds values that are no longer up to date.

Lets say you have a field ‘permission’ in your user table. You decided to use an integer as a simple way to set roles. Anyone with a role of 8 or higher is an admin.

Now you assign user A a role of 8. Later on, you demote him to a role of 6 (for example moderator, but no longer admin). But because user A’s data is in the session, your app won’t check the database, and as such will concider him an admin untill he logs off.

At this point, user A’s session is stale