I tried to organize the session in Rails

We are doing a lot of rails tutorials. About "session" dealt with in Chapter 8, this time I wrote an article that I wanted to organize for my own understanding. Since I am a beginner, I would be grateful if you could point out any mistakes in the comments.

What is a session in the first place? (answer) A "mechanism" that realizes "stateful communication".

What is stateful? The HTML we usually use communicates statelessly. * State less = 1 time 1 time independent exchange

In this communication, the communication between the browser and the server is independent for each round trip. Previous information cannot be inherited.

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

So, ** The session is to make stateless HTML communication "stateful". ** **

  • State (state) full (hold) = exchange while "holding" the state such as user information

In this communication, the browser ⇄ server exchanges information by adding information to the communication. It is possible to make this entire exchange into 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 the member information. On the shopping site, you can put more and more things in the cart, which is convenient.

"Stateful communication" in HTML consists of a mechanism called a session.

Reference: session communication

How are

sessions exchanged? </ h2> (answer) Generally, the session ID included in the "cookie" sent from the browser side The server side acquires and collates, extracts the session contents, and exchanges them. Closing the browser deletes the session.

What is a cookie? In a word, a cookie is information held on the web browser side.

Sessions don't always handle cookies, but they are certainly commonly used. Rails also uses cookies as a standard, so we will assume cookies here.

~ Rough flow of cookies ~

** ① First access ** The browser side accesses the server side. The server side includes the browser identification information (for example, login information) in the HTTP header and sends it. The browser saves that information (this is the cookie information)

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

In this way, the cookie is the information held on the browser side, and by sending it including the session ID, the server side can understand "what kind of content did you exchange?" I will. By the way, the content of session itself is 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 talked about concepts, let's sort out the contents of sessions in Rails. Rails allows you to set up a session for each user. Sessions are only available in controllers and views. You can also select the following storages.
storage Description
ActionDispatch::Session::CookieStore: Save all sessions in a cookie on the client-side browser
ActionDispatch::Session::CacheStore: Save data to Rails cache
ActionDispatch::Session::ActiveRecordStore: Save to database using Active Record(activerecord-session_need store gem)
ActionDispatch::Session::MemCacheStore: Save data to memcached cluster(This implementation is old so you should consider CacheStore)

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

The CookieStore has the following ** benefits **. ・ Very lightweight ・ A set has been prepared for using the session with the web application. -The cookie data is given an encrypted signature to prevent tampering, and the cookie itself is also encrypted, so the contents cannot be read by others (the tampered cookie is rejected by Rails).

However, there are also the following ** disadvantages **. ・ The upper limit of cookies is 4KB -Since the cookie is saved on the client side (browser), the contents of the expired cookie may remain. · Client cookies may be copied to other computers ・ Session cookies do not expire by themselves, so they may be reused for misuse.

Basically, I think it's better to use the CookieStore recommended by Rails, I thought that it was necessary to use it properly according to the situation.

Reference: rails guide session

session operation

The following are all operations in the Cookie Store that is 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])

Information on session can be easily referenced. When the session method is called, the cookie information is decrypted internally and the value can be obtained with session [: symbol].

**-Delete session **

#Everything you do is the same
session[:user_id] = nil
session[:user_id].clear
session.delete(:user_id)

It is possible to rewrite with nil or delete information with clear or delete.

At the end The biggest question I had when learning session was the relationship between session and cookies. The behavior of Rails' session method (CookieStore) is different from what is said in the concept. I don't understand well ,? Is full ... lol

When I organized it again, I was able to identify the points that I did not understand and it was refreshing. I will continue to do my best in the Rails tutorial.

The site that I used as a reference 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

Recommended Posts

I tried to organize the session in Rails
I tried to sort the data in descending order, ascending order / Rails
[Rails] I tried to raise the Rails version from 5.0 to 5.2
I tried to implement the Euclidean algorithm in Java
I tried to explain the method
[Rails] I tried deleting the application
I tried to introduce Bootstrap 4 to the Rails 6 app [for beginners]
I tried to summarize the methods used
I tried to introduce CircleCI 2.0 to Rails app
I tried the new era in Java
I tried to implement the Iterator pattern
I tried to summarize the Stream API
I tried the AutoValue library in Intellij
I tried to summarize the words that I often see in docker-compose.yml
I tried to implement Ajax processing of like function in Rails
I tried to illuminate the Christmas tree in a life game
I tried to implement the image preview function with Rails / jQuery
I tried to understand how the rails method "redirect_to" is defined
I tried to understand how the rails method "link_to" is defined
I tried to implement polymorphic related in Nogizaka.
I tried to implement deep learning in Java
I tried to make the "Select File" button of the sample application created in the Rails tutorial cool
The code I used to connect Rails 3 to PostgreSQL 10
I tried to solve the tribonacci sequence problem in Ruby, with recursion.
I tried to output multiplication table in Java
After learning Progate, I tried to make an SNS application using Rails in the local environment
I tried to set tomcat to run the Servlet.
I tried to build Micra mackerel in 1 hour!
I tried to make full use of the CPU core in Ruby
I tried to develop an application in 2 languages
I tried to create Alexa skill in Java
[Ruby] I tried to summarize the methods that frequently appear in paiza
[Ruby] I tried to summarize the methods that frequently appear in paiza ②
How to check Rails commands in the terminal
I want to get the value in Ruby
I tried to solve the tribonatch sequence problem in Ruby (time limit 10 minutes)
[Rails / JavaScript / Ajax] I tried to create a like function in two ways.
About the case where "Docker" freeter tried to put Docker in the existing Rails application
I was addicted to the NoSuchMethodError in Cloud Endpoints
How to set the display time to Japan time in Rails
I want to embed any TraceId in the log
I tried to implement Firebase push notification in Java
I tried to summarize the state transition of docker
I tried to decorate the simple calendar a little
[Rails] I tried playing with the comment send button
05. I tried to stub the source of Spring Boot
# 2 [Note] I tried to calculate multiplication tables in Java.
I want to use a little icon in Rails
I tried to reduce the capacity of Spring Boot
[Rails] I don't know how to use the model ...
I tried to create a Clova skill in Java
I tried to make a login function in Java
I tried installing the Docker Integration plugin in IntelliJ
I want to define a function in Rails Console
Rails6 I tried to introduce Docker to an existing application
~ I tried to learn functional programming in Java now ~
[Rails] How to display an image in the view
I tried to find out what changed in Java 9
I tried Rails beginner [Chapter 1]
I tried the Docker tutorial!
I tried the VueJS tutorial!