[Ruby] I tried to organize the session in Rails

4 minute read

I am doing a lot of rails tutorials. I wrote an article about “session” which is dealt with in Chapter 8 this time because I want to organize it for my own understanding. Since I am a beginner, I would be grateful if you could point out any comments in the comments.

What is a session in the first place?

(answer) “Mechanism” that realizes “stateful communication”.

What is stateful?

The HTML that we usually use is for stateless communication. *State less = 1 time 1 time independent communication

In this communication, the communication between the browser ⇄ server is independent for each round trip, Previous information cannot be carried over.

However, you may be wondering when you hear this story. If all HTML communication is independent, for example, at a shopping site, When you put the products you want to buy in the cart, information is not carried over, so The cart should be empty when the page transitions.

So, ** the mechanism is to make stateless HTML communication “stateful”. ** *State (state) full (hold) = exchange while keeping the state of user information etc.

In this communication, by adding information to the communication between the browser ⇄ server and exchanging, It is possible to make this whole interaction like a series of actions.

In the above example, on the site where you logged in as a member, you can jump to various pages while retaining member information. At a shopping site, you can put things in your cart one after another, which is very convenient.

“Stateful communication” in HTML consists of a mechanism called session.

Reference: session communication

How are <h2>sessions exchanged? </h2> (answer) Generally, the session ID included in the “cookie” sent from the browser The server side obtains and collates the session contents and exchanges them. The session is deleted by closing the browser.

What is a cookie?

In a nutshell, a cookie is information held by the web browser.

Sessions do not always handle cookies, but they are certainly used in general. Rails also uses cookies as standard, so I will assume cookies here.

~ A rough flow of cookies ~


** ① Access first time ** The browser side accesses the server side. The server side sends the browser’s identification information (eg login information) in the HTTP header. The browser saves that information (cookie information is this)

** ② Access after that ** The browser side includes the saved cookie information in the HTTP header and sends it to the server side. The server side determines the other party who has accessed based on the information.

In this way, the cookie is information held by the browser side, and by sending the session ID included in it, the server side will be able to understand “what kind of content was exchanged?” I will. By the way, the contents of session itself are held by the web server side, and the session ID in the cookie is the ID for calling it.

The session is only temporary and is basically deleted when the browser is closed.

What is a session in Rails?

Now that we’ve covered the concepts, let’s sort out the content of sessions in Rails. With rails, you can set a session for each user. Sessions are only available in controllers and views. You can also select the following storage.

Storage Description
ActionDispatch::Session::CookieStore: Store all sessions in the browser cookie on the client side
ActionDispatch::Session::CacheStore: Save data to Rails cache
ActionDispatch::Session::ActiveRecordStore: Save to database using Active Record (requires activerecord-session_store gem)
ActionDispatch::Session::MemCacheStore: Storing data in memcached cluster (this implementation is outdated, CacheStore should be considered)

As mentioned earlier, basically the session ID is stored in a cookie and passed to the server, Regarding the CookieStore used by default, the **session information itself is saved in the cookie side. **

CookieStore has the following advantages. ・Very lightweight ・A set has been prepared to use the session in the Web application

  • The cookie data is given a cryptographic signature to prevent tampering, and the cookie itself is encrypted, so the contents cannot be read by others (the tampered cookie is rejected by Rails).

However, there are the following Disadvantages. ・Up to 4KB cookie

  • Since the cookie is saved on the client side (browser), the contents of the expired cookie may remain. ・Client’s cookies may be copied to other computers ・Since session cookies do not expire by themselves, they may be reused for misuse.

Basically, I think it’s better to use CookieStore recommended by Rails, but I thought that it was necessary to use them properly depending on the situation.

Reference: rails guide session

Session operation

The following are all operations in CookieStore used by default.

・Create session

session[:user_id] = @user.id

The session method can be set with a hash value. By setting, an encrypted cookie containing the information of this session will be generated.

・Refer to session

user = User.find(id: session[:user_id])

You can easily refer to the session information. When the session method is called, the cookie information is decrypted internally and the value can be obtained with session[:symbol].

Delete session

# Do everything together
session[:user_id] = nil
session[:user_id].clear
session.delete(:user_id)

Information can be deleted by rewriting with nil or clear or delete.

At the end

When I was learning session, I was most skeptical about the relationship between session and cookies. The content of the concept is different from the behavior of the Rails session method (CookieStore). You don’t understand well? Filled with lol

When I reorganized it, I found the points I didn’t understand were clear. I would like to continue working on the Rails tutorial.

Sites that we refer to

Thank you! https://ja.wikipedia.org/wiki/HTTP_cookie https://qiita.com/hththt/items/07136ad74127999df271 https://qiita.com/hot_study_man/items/147f8b767b4135fe6fe4 https://www.justinweiss.com/articles/how-rails-sessions-work/ https://railsguides.jp/security.html

Tags: ,

Updated: