[RUBY] (Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 8]

Premise

・ Rails tutorial is the 4th edition ・ This study is the 3rd lap (2nd lap after Chapter 9) ・ The author is a beginner who has done all of Progate.

Basic policy

・ If you read it, you will not understand it. ・ Search and summarize terms that you do not understand (at the bottom of the article, glossary). ・ Dive into what you do not understand. ・ Work on all exercises. ・ Do not copy chords as much as possible.

Chapter 8 is the development of login and authentication system, the third stage, and the basic login mechanism will be implemented. (We will develop it further in Chapter 9) Information technology terms are scattered around, so let's proceed while understanding the meaning and operation of each term.   Today's BGM has a different taste. TV Anime "Yurucamp △" Original Soundtrack It's finally getting cooler. It's the perfect season for camping. Let's go to refresh the eyes and head tired from coding.

[8.1.1 Sessions controller exercise]

  1. Can you explain the difference between GET login_path and POST login_path? Let's think a little. → GET gets the view of the login page (new action), POST sends the data entered in the form and executes login (create action).

2. By connecting the rails routes execution result and the grep command using the pipe function of the terminal, only the routes related to the Users resource can be displayed. Similarly, let's display only the results for the Sessions resource. How many Sessions resources do you currently have? Tip: If you don't know how to use pipes or grep, check out the Learn Enough Command Line to Be Dangerous Section on Grep. → Pipe function: (command) | (command) A function that connects commands to each other. grep command: A command to search for a character string in a file. So below. Is it unavoidable that signup is included?

$ rails routes | grep users#
      signup GET    /signup(.:format)         users#new
             POST   /signup(.:format)         users#create
       users GET    /users(.:format)          users#index
             POST   /users(.:format)          users#create
    new_user GET    /users/new(.:format)      users#new
   edit_user GET    /users/:id/edit(.:format) users#edit
        user GET    /users/:id(.:format)      users#show
             PATCH  /users/:id(.:format)      users#update
             PUT    /users/:id(.:format)      users#update
             DELETE /users/:id(.:format)      users#destroy
$ rails routes | grep sessions#
    login GET    /login(.:format)          sessions#new
          POST   /login(.:format)          sessions#create
   logout DELETE /logout(.:format)         sessions#destroy

[8.1.2 Login Form Exercise]

  1. When you submit in the form defined in Listing 8.4, you will reach the create action of the Sessions controller. How does Rails do this? Think about it. Tip: Notice the first row in Table 8.1 and Listing 8.5. → It will be a sentence of post'/ login', to:'sessions # create' in the routes file. Issue post request with form_for → Assign to create action of sessions controller by routing.

[8.1.3 User search and authentication exercises]

  1. Using the Rails console, let's check if each expression in Table 8.2 matches. First, check the case where user = nil, and then the case where user = User.first. Tip: Try using the !! technique introduced in 4.2.3 to make sure it's a Boolean object. Example: !! (user && user.authenticate ('foobar')) → Below
>> user = nil
=> nil
>> !!(user && user.authenticate("foobar"))
=> false

>> user = User.first
  User Load (0.1ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
=> #<User id: 1, name: "Rails Tutorial", email: "[email protected]", created_at: "2020-09-12 09:09:50", updated_at: "2020-09-12 09:09:50", password_digest: "$2a$10$hrOEzw0faSd4yurmH8bQJOnggeNnUqTZg33yE9g7Tnk...">
>> !!(user && user.authenticate("matigatteruyo"))
=> false
>> !!(user && user.authenticate("hogehoge"))
=> true

[8.1.5 Flash test exercise]

  1. Please check with your browser whether the processing flow of 8.1.4 is working properly. In particular, don't forget to go to a different page after displaying the flash message to see if flash is working well. → Let's try it. If you go to a different page, the flash will go out.

[8.2.1 log_in method exercise]

  1. Please log in as a valid user and check the cookies information from your browser. What's the value of session at this point? Tip: Don't know how to look up cookies in a browser? Now is the time to google! (Column 1.1)
  2. As with the previous exercise, check the value of Expires. → Collectively, the image below. Expires = Expires, so it's inside the green square. The expiration date is at the end of the browser session. スクリーンショット 2020-09-13 14.16.12.png

[8.2.2 Current user exercises]

  1. Using the Rails console, let's confirm that User.find_by (id: ...) returns nil when the corresponding user is not found in the search. → Below
>> User.find_by(id: 8)
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 8], ["LIMIT", 1]]
=> nil

2.As before, this time:user_Let's create a session hash with an id key. Listing 8.Follow the steps described in 17.||=Let's also check that the operator works well. → Below

>> session = {}
=> {}
>> session[:user_id] = nil
=> nil
>> @current_user ||= User.find_by(id: session[:user_id])
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ?  [["LIMIT", 1]]
=> nil
>> session[:user_id] = User.first.id
  User Load (0.1ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
=> 1
>> @current_user ||= User.find_by(id: session[:user_id])
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
=> #<User id: 1, name: "Rails Tutorial", email: "[email protected]", created_at: "2020-09-12 09:09:50", updated_at: "2020-09-12 09:09:50", password_digest: "$2a$10$hrOEzw0faSd4yurmH8bQJOnggeNnUqTZg33yE9g7Tnk...">
>> @current_user ||= User.find_by(id: session[:user_id])
=> #<User id: 1, name: "Rails Tutorial", email: "[email protected]", created_at: "2020-09-12 09:09:50", updated_at: "2020-09-12 09:09:50", password_digest: "$2a$10$hrOEzw0faSd4yurmH8bQJOnggeNnUqTZg33yE9g7Tnk...">

[8.2.3 Exercise to change layout link]

  1. Try deleting the session cookie using the cookie inspector function of your browser (8.2.1.1). Is the link in the header part unlogged in? Let's check. → Just try it. You are now in a non-logged-in state.

2. Try logging in again and see that the header layout has changed. After that, restart your browser and check that you are back in the non-logged-in state again. Note: If you turn on the browser's "Restore to Closed State" feature, session information may also be restored. If you have that feature turned on, don't forget to turn it off (Column 1.1). → Just try it.

[8.2.4 Notes and exercises to test layout changes]

Is the code for the digest method here honest? ?? Status. What does it mean to write two :? It's been coming out from the front. If you look it up, PHP notation comes out, is it good for the same meaning? Test assertions are summarized in a glossary.

  1. Try removing! From the session helper's logged_in? method and see that Listing 8.23 turns red.
  2. Restore the deleted part (!) And check that the test returns to green. → Collectively. Of course it will fail. The header display will be reversed when logged in or not logged in. If you put it back, it's GREEN.

[8.2.5 Login memo and exercise when registering as a user]

You have defined various helper methods in this chapter. Write your code while being aware of where you are defining it for use. Whether to use it in a controller or in a test, etc.

  1. If I comment out the log_in line in Listing 8.25, will the test suite be red or green? Let's check. → It will be RED. I'm writing code to check if I'm logged in to the test.

2. Use the function of the text editor you are currently using to check if you can comment out the list 8.25 at once. Also, run the test suite before and after commenting out and make sure it turns red when commented out and green when commented out. Tip: Don't forget to save the file after commenting it out. Also, see Commenting Out in the Test Editor Tutorial for more information on the commenting out function of the text editor. → (For Mac) Command + A to select all, command + / to comment out. Of course, it will be RED / GREEN before and after commenting out.

[8.3 Logout memos and exercises]

  1. Click the [Log out] link from your browser and see what happens. Also, try the three steps defined in Listing 8.31 to see if it works. → It works properly.

2. Check the contents of cookies and confirm that session has been deleted normally after logging out. → It has been deleted.

Chapter 8 Summary

-Temporary state save with session method. -Since the User model of Active Record is not used for login, the associated error message cannot be used. -Display flash messages only for pages rendered with flash.now. ・ Form_for seems to be replaced with form_with, so for reference. -Render and redirect_to are used properly. -Display a flash message. -Integration test tests the implementation around login (whether login / logout is possible, header is switched)

This chapter went on without major errors. We will introduce an advanced mechanism from the next chapter 9. At last, we will enter the chapter that has only one lap! Let's get excited!

Go to Chapter 9! Click here for Chapter 7 Click here for premise and author status for learning

A glossary that somehow captures the image

・ Stateless protocol Independent exchange of information that does not maintain state. If you compare it to the login function, if you close the browser and then re-enter, you will be logged in again.

・ Session A series of communications (from login to logout, etc.). On the website, this is the identifier that is written in the cookie of the browser when you visit for the first time.

・ Cookie A communication protocol that manages the state between a web server and a web browser in HTTP, and information stored in the web browser used there. It is used in shopping carts and login functions on EC sites. You can erase it from your browser settings, thinking that it has accumulated.

・ Assert_redirected_to Test whether the redirect destination called immediately before this assertion matches the redirect destination below to.

・ Follow_redirect! Actually move to that page. Used when testing other elements at the destination.

Recommended Posts

(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 11]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 1]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 14]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 12]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 5]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 4]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 8]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 6]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 13]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 9]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 10]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 7]
(Giri) A local government employee in his twenties works on a Rails tutorial [Chapter 2]
(Giri) A local government employee in his twenties works on a Rails tutorial [Introduction]
[Ruby on Rails Tutorial] Error in the test in Chapter 3
[Rails Tutorial Chapter 5] Create a layout
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 6
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 3
(Ruby on Rails6) Creating data in a table
[Rails tutorial] A memorandum of "Chapter 11 Account Activation"
rails tutorial Chapter 6
rails tutorial Chapter 1
rails tutorial Chapter 7
rails tutorial Chapter 5
rails tutorial Chapter 10
rails tutorial Chapter 9
rails tutorial Chapter 8
[Rails Tutorial Chapter 2] What to do when you make a mistake in the column name
Rails Tutorial Chapter 10 Notes
Rails Tutorial Chapter 3 Notes
Rails Tutorial Chapter 3 Learning
Rails Tutorial Memorandum (Chapter 3, 3.1)
Rails Tutorial Chapter 4 Notes
Rails Tutorial Chapter 4 Learning
Rails Tutorial Chapter 1 Learning
Rails Tutorial Chapter 2 Learning
Rails Tutorial Chapter 8 Notes
Rails Tutorial Memorandum (Chapter 3, 3.3.2)
Difficulties in building a Ruby on Rails environment (Windows 10) (SQLite3)
How to display a graph in Ruby on Rails (LazyHighChart)
Apply CSS to a specific View in Ruby on Rails