原文:http://www.justinweiss.com/articles/how-rails-sessions-work/
If you were keeping track of your sessions with ActiveRecord:
- When you call session[:current_user_id] = 1 in your app, and a session doesn’t already exist:
- Rails will create a new record in your sessions table with a random session ID (say, 09497d46978bf6f32265fefb5cc52264).
- It’ll store {current_user_id: 1} (Base64-encoded) in the data attribute of that record.
- And it’ll return the generated session ID, 09497d46978bf6f32265fefb5cc52264, to the browser using Set-Cookie.
The next time you request a page,
- The browser sends that same cookie to your app, using the Cookie: header.
(like this: Cookie: _my_app_session=09497d46978bf6f32265fefb5cc52264;
path=/; HttpOnly) - When you call session[:current_user_id]:
- Your app grabs the session ID out of your cookie, and finds its record in the sessions table.
- Then, it returns current_user_id out of the data attribute of that record.
Whether you’re storing sessions in the database, in Memcached, in Redis, or wherever else, they mostly follow this same process. Your cookie only contains a session ID, and your Rails app looks up the data in your session store using that ID.