Ruby on Rails includes some options for handling sessions (see overview by Stefan Kaes (PDF)). Unfortunately the default ActiveRecord session handler is relatively slow which may have a big impact on your application (sessions tend to accumulate quickly). Fortunately for all of us, Stefan has created an alternative MySQL session handler whith hard coded SQL statements. His version is much quicker.

If your application uses the standard session handler there is really no reason not to implement Stefan’s solution. However, to make it work with the default session table created by Rails 1.1.2 you have to do some minor modifications (at least in version 0.2):

  1. Download and install Stefan’s session handler files into your application’s lib directory.
  2. If you haven’t created the session table for your application, run “rake create_sessions_table”. The will add a new migration file in the db/migrate folder.
  3. Update the migration file to make sure the created_at column is included. You can append it by adding “t.column :created_at, :datetime”.
  4. Open lib/sql_session_store.rb and modify the SQL statements containing a reference to the sessid column. In Rails 1.1.2 this should be called “session_id”.
  5. Update your config/environment.rb by appending the following lines at the end of the file:
require 'sql_session_store'
require 'mysql_session'
ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.update(:database_manager => SQLSessionStore)
SQLSessionStore.session_class = MysqlSession

Restart your web server and you have improved session performance a lot. For more details see: