[RUBY] rails tutorial Chapter 8


I will post the process of advancing the rails tutorial on my own.

It touches on words that I didn't understand in the process, jammed errors, and so on.

Please point out any mistakes as it is an output of personal learning.

Since this is my first post, I think there are many places that are difficult to read, but please forgive me.

Chapter 8 Basic Login Mechanism

8.1.2 Login form

I didn't understand how scope works when creating the login form, so I looked it up.

form_with(url: login_path, scope: :session, local: true)

reference https://qiita.com/akilax/items/f36b13f377f7e442bc73

It seems good to think of it as the prefix of the name value needed when passing parameters without thinking too much.

Roughly speaking, in the form of an object that inherits Active Recode

<%= form_with(model: @user, local: true) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name, class: 'form-control' %>
<% end %>

And access to the input value (name value of the generated input tag)


And the input result was saved in the user hash.

The same is true for this session form, and I think that the input result is saved in the hash specified by scope in order to pass the value of the input result to the parameter.

8.1.4 Display a flash message

Displays an error message when login fails.


#Listing 8.8:Handles processing when login fails (with error)
class SessionsController < ApplicationController

  def new

  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      #Redirect to user information page after user login
      flash[:danger] = 'Invalid email/password combination' #Not really correct
      render 'new'

  def destroy

In fact, with the above code, once the request flash message is displayed, it will not disappear. Unlike when using redirects in Listing 7.27, forcing the render method to re-render the displayed template is not considered a request, so the request message does not disappear. For example, if you deliberately enter invalid information and send it to display an error message, then click on the Home page to go to it, the flash message will still be displayed there. (rails tutorial Quoted from Chapter 8)

Here, the question arises as to why the message does not disappear unless it is regarded as a request, and whether it can be deleted because a GET request is made when clicking the home page after displaying the error message. I did.

To solve this question, I first investigated the difference between render and redirect_to.

reference https://qiita.com/january108/items/54143581ab1f03deefa1 After reading this article, I still had the question that I made a request when I clicked on the home page. After that, I researched various things and finally arrived at the answer. Apparently I didn't understand enough about flash.

reference https://pikawaka.com/rails/flash

In other words, it seems that the flash message is displayed, then the request is received, the action is performed, and then the flash message is cleared.

So after the view was displayed with the render method, it seemed that the message remained even if I made a home request.

As a test

  1. Enter invalid information and send
  2. Check the error message
  3. Go to home page
  4. Make sure that the error message does not disappear on the home page
  5. Click the home page again Then the error message disappeared.

It was really refreshing !!

8.2 Login

Rails session helpers are also automatically loaded into the view. If you load this module into the Application controller, which is the parent class of all Rails controllers, you can use it with any controller. (rails tutorial Quoted from Chapter 8)

Caution It is automatically loaded in view, but if you want to use the method set in the helper with a controller etc., you need to load it with include.

8.2.2 Current user

There is something difficult to understand on this topic, so I used the question on Qiita for the first time.

When I dug deeper into the content, I didn't understand why I should have used the find_by method instead of the find method, so I asked a question.

Contents of question https://qiita.com/shun_study_p/questions/da3de50fe7826dc151ed Thank you to those who answered.

@current_user ||= User.find_by(id: session[:user_id])

The logical value of the User object itself is always true. Thanks to that, the find_by call is executed only when nothing is assigned to @current_user, and no useless read to the database is done. (rails tutorial Quoted from Chapter 8)

Supplement the sentence here as well

@current_user ||= User.find_by(id: session[:user_id])

This sentence is to execute the find_by method and create a User object when @current_user is nil. (User object is assigned to @current_user) After that, @current_user becomes a User object, and since the User object returns true, the left side becomes true after that, the useless find_by method is not executed (because @current_user is not nil), and useless data is called. Will not be done.

8.2.3 Change layout link

<%= link_to "Profile", current_user %>

What is being done in this sentence as a review

<%= link_to "Profile", "/users/#{current_user.id}" %>
<%= link_to "Profile", user_path(current_user.id) %>
<%= link_to "Profile", user_path(current_user) %>
<%= link_to "Profile", current_user %>

Is abbreviated.

Another question here is You can see that we pass the model object as an argument to link_to.

But this time it's not a method ...?

Regarding this, I referred to the following article.

Reference article 1 (also referred to in Chapter 7) https://qiita.com/Kawanji01/items/96fff507ed2f75403ecb

Reference article 2 https://teratail.com/questions/198096 Apparently, if you return an instance of the model in the return value, you can think of the method as a model object.

8.2.4 Test layout changes

def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
    BCrypt::Password.create(string, cost: cost)

This digest method will be used in various situations in the future. For example, 9.1.1 will reuse digest, so let's put this digest method in the User model (user.rb). You don't have to do this calculation on a per-user basis, so you don't have to bother accessing the user object, such as in a fixture file (that is, you don't have to define it in an instance method). (rails tutorial Quoted from Chapter 8)

I don't understand the meaning of the above sentence, maybe I didn't understand the difference between the instance method and the class method.

The text above is

  1. If you define it with an instance method, you need to access the user object.
  2. This "digest method that returns the hash of the passed string" does not need to be performed on each user instance. (What you can do directly from the class object)

they said. Somehow, I can understand what these two mean ...

It's still a fluffy understanding, but I tried to summarize it myself by referring to the article.

reference https://qiita.com/tbpgr/items/56eb65c0ea5882abbb07

In other words Class methods have the role of changing and referencing information about the XX class itself.

So password hashing like this one, gender attributes such as gender as in the example of the article, these can be defined in advance with class methods.

Instance methods have the role of changing and referencing information about individual instances.

Therefore, when you want to refer to information such as password or name of specific data, use instance method. (It's easy to imagine that you need to access the user object)

I wonder if it's such a place ... difficult ...

At the end

This chapter is also difficult, and there are some parts that have progressed with about 70% understanding, so I thought it was necessary to review again.

Recommended Posts

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 5 Notes
Rails Tutorial Memorandum (Chapter 3, 3.1)
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)
rails tutorial
rails tutorial
rails tutorial
rails tutorial
rails tutorial
rails tutorial
[Rails Tutorial Chapter 4] Rails-flavored Ruby
[Rails Struggle/Rails Tutorial] Summary of Rails Tutorial Chapter 2
Rails tutorial test
[Rails Tutorial Chapter 5] Create a layout
rails tutorial chapter 10 summary (for self-learning)
Rails tutorial memorandum 1
Rails tutorial memorandum 2
Chewing Rails Tutorial [Chapter 2 Toy Application]
Start Rails Tutorial
[Beginner] Rails Tutorial
Rails Tutorial (4th Edition) Memo Chapter 6
Rails Tutorial 6th Edition Learning Summary Chapter 10
Rails Tutorial 6th Edition Learning Summary Chapter 7
Rails Tutorial 6th Edition Learning Summary Chapter 4
Rails Tutorial 6th Edition Learning Summary Chapter 6
Rails Tutorial 6th Edition Learning Summary Chapter 5
Rails Tutorial 6th Edition Learning Summary Chapter 2
Rails Tutorial Chapter 0: Preliminary Basic Knowledge Learning 5
Rails Tutorial 6th Edition Learning Summary Chapter 3
Rails Tutorial 6th Edition Learning Summary Chapter 8
Chapter 4 Rails Flavored Ruby
Rails Tutorial cheat sheet
[Rails] Learning with Rails tutorial
rails tutorial fighting notes Ⅲ
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 6
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 3
Rails Tutorial Chapter 1 From Zero to Deployment [Try]
Chewing Rails Tutorial [Chapter 3 Creating Almost Static Pages]
[Rails tutorial] A memorandum of "Chapter 11 Account Activation"
Resolve Gem :: FilePermissionError when running gem install rails (Rails Tutorial Chapter 1)
[Ruby on Rails Tutorial] Error in the test in Chapter 3
11.1 AccountActivations Resources: Rails Tutorial Notes-Chapter 11
Rails Tutorial Records and Memorandum # 0
I tried Rails beginner [Chapter 1]
Rails Tutorial (4th Edition) Summary
Rails Tutorial 4th Edition: Chapter 1 From Zero to Deployment
Resolve ActiveRecord :: NoDatabaseError when doing rails test (Rails tutorial Chapter 3)
I tried Rails beginner [Chapter 2]
[Rails] Implementation of tutorial function
Chewing Rails Tutorial [Chapter 1 From Zero to Deployment] First Half
Rails Tutorial Chapter 14 Creating Relationship Test Data with Factory Bot