Session objects are used in ROR to store small amount of information which can be used later on. In fact websites following http (a stateless protocol) use session object to keep logged in user informations so that those informations persists between requests from the user.Sessions makes HTTP stateful.
When a user logs in a website , a hash of values and a session id is created in the hosting server which are collectively known as session of the user . This is send back in the response from the server as a cookie.This session id is a unique string of 32 character and is used to identify the users session . This session id is stored in a cookie in the clients browser and is sent with every request made by the user to the server. In controller we can retrieve the user from session as:
There are different mechanism for storing the session. They are:
ActionDispatch::Session::CookieStore: This mechanism use client side cookie to store session. Storing session in cookie is easy and can be done without any extra setup. The maximum size is 4kb and storing data larger than this size is not recommended.
ActionDispatch::Session::CacheStore: This mechanism use rails cache to store session. If the session is not holding sensitive data then we can use cache to store the session. This mechanism has the advantage that no additional setup is required,and Rails use its own default caching infrastructure.
ActiveRecord::SessionStore: This mechanism use the database for storing the session data.
The session hash and the session id is saved in the database. This process is more secure than the cookiestore and most of the live application try to follow this.
To use Sessionstore we need to create a table (session_migration) in the database with the following columns in it id(integer), session_id(string), data(text). The session_id can be indexed for better performance. Once the table is created we have to change the settings of the config/initializers/session_store.rb.