Setting and Retrieving Session Information

Problem

You want to associate some data with each distinct web client thats using your application. The data needs to persist across HTTP requests.

Solution

You can use cookies (see Recipe 15.12) but its usually simpler to put the data in a users session. Every visitor to your Rails site is automatically given a session cookie. Rails keys the value of the cookie to a hash of arbitrary data on the server.

Throughout your entire Rails application, in controllers, views, helpers, and mailers, you can access this hash by calling a method called session. The objects stored in this hash are persisted across requests by the same web browser.

This code in a controller tracks the time of a clients first visit to your web site:

class IndexController < ApplicationController def index session[:first_time] ||= Time.now end end

Within your view, you can write the following code to display the time:[4]

[4] The helper function time_ago_in_words( ) calculates how long its been since a certain time and returns English text such as "about a minute" or "5 hours" or "2 days". This is a nice, easy way to give the user a perspective on what a date means.

You first visited this site on <%= session[:first_time] %>. That was <%= time_ago_in_words session[:first_time] %> ago.

Discussion

Cookies and sessions are very similar. They both store persistent data about a visitor to your site. They both let you implement stateful operations on top of HTTP, which has no state of its own. The main difference between cookies and sessions is that with cookies, all the data is stored on your visitors computers in little cookie files. With sessions, all the data is stored on the web server. The client only keeps a small session cookie, which contains a unique ID thats tied to the data on the server. No personal data is ever stored on the visitors computer.

There are a number of reasons why you might want to use sessions instead of cookies:

On the other hand, cookies are useful when:

Generally, its a better idea to use sessions than to store data in cookies.

You can include model objects in your session: this can save a lot of trouble over retrieving the same objects from the database on every request. However, if you are going to do this, its a good idea to list in your application controller all the models youll be putting into the session. This reduces the risk that Rails won be able to deserialize the objects when retrieving them from the session store.

class ApplicationController < ActionController::Base model :user, :ticket, :item, :history end

Then you can put ActiveRecord objects into a session:

class IndexController < ApplicationController def index session[:user] ||= User.find(params[:id]) end end

If your site doesn need to store any information in sessions, you can disable the feature by adding the following code to your app/controllers/application.rb file:

class ApplicationController < ActionController::Base session :off end

As you may have guessed, you can also use the session method to turn sessions off for a single controller:

class MyController < ApplicationController session :off end

You can even bring it down to an action level:

class MyController < ApplicationController session :off, :only => [index] def index #This action will not have any sessions available to it end end

The session interface is intended for data that persists over many actions, possibly over the users entire visit to the site. If you just need to pass an object (like a status message) to the next action, its simpler to use the flash construct described in Recipe 15.8:

flash[:error] = Invalid login.

By default, Rails sessions are stored on the server via the PStore mechanism. This mechanism uses Marshal to serialize session data to temporary files. This approach works well for small sites, but if your site will be getting a lot of visitors or you need to run your Rails application concurrently on multiple servers, you should explore some of the alternatives.

The three main alternatives are ActiveRecordStore, DRbStore, and MemCacheStore. ActiveRecordStore keeps session information in a database table: you can set up the table by running rake create_sessions_table on the command line. Both DRbStore and MemCacheStore create an in-memory hash thats accessible over the network, but they use different libraries.

Ruby comes with a standard library called DRb that allows you to share objects (including hashes) over the network. Ruby also has a binding to the Memcached daemon, which has been used to help scale web sites like Slashdot and LiveJournal. Memcached works like a direct store into RAM, and can be distributed automatically over various computers without any special configuration.

To change the session storing mechanism, edit your config/environment.rb file like this:

Rails::Initializer.run do |config| config.action_controller.session_store = :active_record_store end

See Also

Категории