unknown wrote in post #1114514:
I’m learning RoR and i would like to know more about the sessions in RoR
Can anyone give me a good example for a session in a web application? or
good pages for learning?
(not: http://ruby.railstutorial.org/ruby-on-rails-tutorial-book :P)
There’s really not a lot that you have to know about sessions in Rails.
You can just think about them as a hash used to store small bits of
information that you want to make available to all controller actions.
For example if you want to remember the id of the logged in user, then
in your action that authenticates you would store the user object’s id
in the session hash:
session[:user_id] = current_user.id
By default Rails is configured to store session data in browser cookies.
Every request included the session cookie. Rails will automatically read
the cookie and create a Ruby Hash named session.
Browser cookies are limited to 4K of data so it is good practice to keep
session data as small as possible. Notice above we do not store the
entire User object in the session, but only store the id of the user.
Whenever you want the details about the user then you can lookup full
user object by the stored id.
There are several other option for storing session data. The data could
be stored in the database using ActiveRecord. Or could be stored in a
memcached, redis, or other NoSQL persistence service.
Note that if you choose an alternative persistent store for your session
data then it will be your responsibility to cleanup old sessions. Rails
will not do that for you automatically. That’s one major advantage of
storing sessions in cookies. It eliminates the need to manage old
sessions. The only drawback I see is the 4K limit, but that should be
plenty of space for the types of information you should keep in
Also it’s worth noting that Rails 4 will begin encrypting the data in
session cookies. Rails 3.2.x signs the cookies to prevent tampering, but
does not encrypt the contents of the cookies.
Just remember that any data stored in a session has to be loaded on
EVERY request, regardless of whether the data is used by the action or
not, so keep session data as small as possible.