Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How session works in Rails

I Learn about session in rails. Most of the reference says that, the following is the way to create a session.

Example:

session[:id]=user.id

Session is a global hash. My doubt is, if session is a global hash, then If more than one user try's to login, then the session variable gets overwrite or not ? Because, there will be only one global hash. So, if millions of user gets login, then how the same "session[:id]" hold all the users sessions. Is it possible to store more than one value in a single variable. And also how to delete a session for a particular user. So, how session is handled in rails?

like image 711
mohangraj Avatar asked Jan 06 '23 08:01

mohangraj


1 Answers

session is not a global hash. It's a method that returns a new hash in the context of each request. How that hash is created depends on the underlying session store.

Let's take a look at 2 typical session stores.

Encrypted cookie store

This is the default session store of Rails applications. Rails serializes then encrypts the whole session hashes into cookies, and stores those cookies on the clients (e.g. browsers). Each time a request hits Rails app, Rails decrypts then deserializes that session cookie to a hash. That hash is what the method session returns.

Redis session store

This session store is not shipped with Rails. It's a separate gem.

With this session store, Rails serializes the session, gives it an ID (called session ID), and stores the ID-hash pair into Redis. Rails then set the session ID to cookie and send that cookie to the client. Each time a request hits Rails app, Rails retrieves the session ID from the cookie, gets the serialized session associated with that session ID from Redis, and deserializes that into a hash. That hash is what the method session returns.

like image 53
Aetherus Avatar answered Jan 12 '23 15:01

Aetherus