You want to associate some data with each distinct web client that's using your application. The data needs to persist across HTTP requests.
Throughout your entire Rails application, in controllers, views,
helpers, and mailers, you can access this hash by calling a method
session. The objects stored
in this hash are persisted across requests by the same web
This code in a controller tracks the time of a client's 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:
<!-- index.rhtml --> You first visited this site on <%= session[:first_time] %>. That was <%= time_ago_in_words session[:first_time] %> ago.
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 ...