Ruby on Rails 4 Session Cookie

12.29.2014

HTTP is a stateless protocol. Sessions make it “stateful”. Session data can be stored on the client side or server side.

Client Side

Rails 4 default session storage is CookieStore. All session data is stored on the client side. There is a 4kb limit.

rails session cookie

Server Side

Session data is stored on the server side. The corresponding session id would be stored in a cookie on the client side.

session datastore

 

Session Store Options

ActionDispatch::Session::CookieStore – Stores everything on the client.
ActionDispatch::Session::CacheStore – Stores the data in the Rails cache.
ActionDispatch::Session::ActiveRecordStore – Stores the data in a database using Active Record. (require activerecord-session_store gem).
ActionDispatch::Session::MemCacheStore – Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).

Some Tips for Working With Sessions

Firebug – There is a very useful cookie inspector.

In Rails, if you use pry in a controller, you can enter session.to_hash to inspect the session. Alternatively, you could use <%= debug session.to_hash %> in the view to inspect the session.

You can set session data with session[:foo] = "bar".

If you want to see the code responsible for encryption. Do bundle open activesupport and find message_encryptor.rb. bundle open actionpack and find cookies.rb.

Sources

http://pothibo.com/2013/09/sessions-and-cookies-in-ruby-on-rails/

http://guides.rubyonrails.org/security.html#sessions

http://machinesaredigging.com/2013/10/29/how-does-a-web-session-work/

http://railscasts.com/episodes/84-cookie-based-session-store?view=comments

http://guides.rubyonrails.org/action_controller_overview.html#session