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


・ 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.

Authentication system development, 5th stage, finally double-digit, Chapter 10 has entered. Let's complete the REST action.   Click here for today's BGM. PLASTIC GIRL IN CLOSET "TOY" Will it be an album 10 years ago ... Time goes by quickly. Sora, my twenties are over.

[10.1.1 Editing form memo and exercise]

-If you put target = "\ _ blank" in the a tag of the link, the link will be opened in another tab. (Security measures are exercises) -Rails internally determines whether it is a new user or an existing user using the new_record method of Active Record.

  1. As mentioned earlier, there is a small security issue when opening a new page with target = "_ blank". The point is that the linked site can handle the window object of the HTML document. Specifically, it can lead to the introduction of malicious content, such as phishing sites. I don't think this will happen on a well-known site like Gravatar, but just in case, let's eliminate this security risk as well. The workaround is to simply set the rel (relationship) attribute of the a tag for the link to "noopener". Let's quickly set this to the link to the Gravatar edit page used in Listing 10.2. → Below.
<a href="http://gravatar.com/emails" target="_blank" rel="noopener">change</a>

2. Let's refactor the new.html.erb view (Listing 10.6) and the edit.html.erb view (Listing 10.7) using the partials in Listing 10.5 (let's remove the code duplication). Tip: You can use the provide method used in 3.4.3 to remove the duplicates 3. (If you have already solved the exercise in related list 7.27, you may not be able to solve this exercise well. If you are not, try to tackle this exercise while thinking about what is different in your existing code. Let's say, for example, I would use the technique of passing variables used in Listing 10.5 to pass the URLs needed in Listing 10.6 and Listing 10.7 to Listing 10.5.) → Just do it. (For some reason, I was doing the exercises in Chapter 7, but there was no difference between the views. Did I return it when I was thinking?)

[10.1.2 Editing failure exercise]

  1. If you send from the edit form using an invalid user name, email address, or password, make sure that editing fails. → I was properly returned to the edit page and got an error.

[10.1.3 Test exercise when editing fails]

  1. Add a line to the test in Listing 10.9 and test if the correct number of error messages are displayed. Tip: Use the assert_select presented in Table 5.2 to find the div tag for the alert class and scrutinize the text "The form contains 4 errors." → Below
assert_select "div.alert", "The form contains 4 errors."

[10.1.4 Exercise to succeed in editing with TDD]

  1. Let's send valid information and check whether the editing actually succeeds.

  2. If you change to an appropriate email address that is not linked to Gravatar (such as [email protected]), how will your profile image be displayed? Actually change the email address from the edit form and change it. Let's check. → Collectively, change the address of the sample user appropriately → Success, the default image of Gravatar is displayed.

[10.2 Approval memo]

Authentication: Identifies the user of the site Authorization: Manages the operations that a user can perform

[10.2.1 Notes and exercises that require users to log in]

before_action: In the controller, execute a specific method just before any action is executed. Apply only to a specific action by passing only: [: action] to the option.

  1. The default before filter imposes restrictions on all actions. In this case, the login page and user registration page should also be limited (and the test should fail as a result). Try commenting out the only: option in Listing 10.15 to see if the test suite can detect the error (whether the test fails). → Yes, RED !

[10.2.2 Exercise to request the correct user]

  1. Why do we need to protect both the edit and update actions? Think about it. → From the URL of the users resource is different (edit is / users / 1 / edit, update is / users / 1). See Table 7.1 in Chapter 7.

2. Which of the above actions can be easily tested in a browser? → Edit, right? Because the HTTP request is GET. It will be displayed in the browser.

[10.2.3 Friendly forwarding memos and exercises]

request object: Refer to Rails Guide. Besides the URL, it also contains various client-side information.

  1. Let's write a test and confirm that it is forwarded only for the first time to the passed URL by friendly forwarding. The next time you log in, the destination URL must return to the default (profile screen). Tip: Let's add a test to see if session [: forwarding_url] in Listing 10.29 is the correct value. → I didn't understand this. The result of the investigation is as follows. In this test, we are trying to access edit_user_path (@user) first, so check if session [: forwarding_url] is equal to that URL. And after logging in, check if you are back to edit_user_url (@user) that you were trying to access, and make sure that session [: forwarding_url] is nil (deleted). got it~.


  test "successful edit with friendly forwarding" do
    get edit_user_path(@user)
    assert_equal session[:forwarding_url], edit_user_url(@user)
    assert_redirected_to edit_user_url(@user)
    assert_nil session[:forwarding_url]
    assert_redirected_to edit_user_url(@user)
    name = "Foo Bar"
    email = "[email protected]"
    patch user_path(@user), params: { user: {name: name,
                            email: email,
                            password: "",
                            password_confirmation: "" } }
    assert_not flash.empty?
    assert_redirected_to @user
    assert_equal name, @user.name
    assert_equal email, @user.email

2. Let's put the debugger method introduced in 7.1.3 in the new action of the Sessions controller. Then log out and try accessing / users / 1 / edit (the debugger should stop prematurely). Now let's move to the console and check if the value of session [: forwarding_url] is correct. Also, check the value of request.get? When accessing the new action (when using the debugger, the terminal sometimes stops at unexpected places or behaves strangely. Skilled I feel like I've become a developer of (Column 1.1), so let's calm down and deal with it). → If you enter session [: forwarding_url] in (byebug), the stored URL (~ / users / 1 / edit) will be displayed, and if you enter request.get ?, true will be returned.

[10.3.1 User list page exercise]

  1. Let's write an integration test for all the links in the layout. Think about the correct behavior for each logged-in user and non-logged-in user. Tip: Let's add a test to Listing 5.32 using the log_in_as helper. → ** The code below that I wrote for trial was GREEN, but is it useless? Moreover, there are 2 patterns. ** **


require 'test_helper'

class SiteLayoutTest < ActionDispatch::IntegrationTest
  def setup
    @user = users(:michael)
  test "layout links" do
    get root_path
    assert_template 'static_pages/home'
    assert_select "a[href=?]", root_path, count: 2
    assert_select "a[href=?]", help_path
    assert_select "a[href=?]", about_path
    assert_select "a[href=?]", contact_path
    assert_select "a[href=?]", signup_path
    get contact_path
    assert_select "title", full_title("Contact")
    get signup_path
    assert_select "title", full_title("Sign up")
    follow_redirect!  #Or get user_path(@user)
    assert_select "a[href=?]", users_path
    assert_select "a[href=?]", user_path(@user)
    assert_select "a[href=?]", edit_user_path(@user)
    assert_select "a[href=?]", logout_path

** Differences from other exercise summaries I examined ** -The logged-in user test is separated from the non-logged-in test. ⇨ It may be better to separate this considering the readability of the code. After that, is it more reliable as a test to clearly separate the operations?

-Get root_path after logging in. ⇨ Isn't this unnatural? Does the default behavior after login jump to the user page? Why bother to go home? So, since log_in_as makes a post request, I thought that I could actually go to that page with follow_redirect! And test it, or I could specify the page to be tested with get user_path (@user). If a problem appears later, we will review it.

[10.3.2 Sample user memos and exercises]

When I put the faker gem here, red letters appeared, so bundle update. I'm getting used to this kind of thing.

  1. Try accessing someone else's edit page and see if you are redirected as implemented in 10.2.2. → If you try to access ~ / user / 2 / edit, you will be skipped to home.

[10.3.3 Pagination Exercise]

  1. Open the Rails console, set nil in the page option and execute it, and let's confirm that the user on the first page can get it. → Below
>> User.paginate(page: nil)
  User Load (1.0ms)  SELECT  "users".* FROM "users" LIMIT ? OFFSET ?  [["LIMIT", 11], ["OFFSET", 0]]
   (0.2ms)  SELECT COUNT(*) FROM "users"
=> #<ActiveRecord::Relation [#<User id: 1, name: "Example User", email: "exam[email protected]", 
Below, omitted because it is long

2. What class is the pagination object acquired in the previous exercise? Also, how is it different from the User.all class? Compare it. → User :: ActiveRecord_Relation class. It's the same.

>> User.paginate(page: nil).class
=> User::ActiveRecord_Relation
>> User.paginate(page: nil).class.superclass
=> ActiveRecord::Relation
>> User.all.class
=> User::ActiveRecord_Relation

[10.3.4 User list test memos and exercises]

There are many other methods of pagination, such as Kaminari and Pagy. (Let's try it in the future)

  1. Try commenting out both pagination links (will_paginate part) in Listing 10.45 to see if the test in Listing 10.48 turns red. → Of course it is RED.

2. I commented out both of them earlier, but if you comment out only one, let's make sure that the test remains green. What test should I add if I want to test that both will_paginate links exist? Tip: Refer to Table 5.2 and add a test to count the number. Let's do it. → Since it is still GREEN, count: 2 is added.


test "index including pagination" do
    get users_path
    assert_template 'users/index'
    assert_select 'div.pagination', count: 2
    User.paginate(page: 1).each do |user|
      assert_select 'a[href=?]', user_path(user), text: user.name

[10.3.5 Partial refactoring exercise]

  1. Comment out the render line in Listing 10.52 and see that the test result turns red. → It will be RED.

[10.4.1 Administrative user exercise]

  1. Let's confirm that the admin attribute cannot be changed via the Web. Specifically, try creating a test that sends a patch directly to the user's URL (/ users /: id), as shown in Listing 10.56. To be sure that your tests are behaving correctly, let's start by adding admin to the list of allowed parameters in the user_params method. The result of the first test should be red. → I didn't know what to put in FILL_IN, so I looked it up and found the answer below. (First, add: admin to permit of user_params method in User controller)


  test "should not allow the admin attribute to be edited via the web" do
    assert_not @other_user.admin?
    patch user_path(@other_user), params: {
                                    user: { password:              @other_user.password,
                                            password_confirmation: @other_user.password,
                                            admin: true } }
    assert_not @other_user.reload.admin?

What? But will it be GREEN? Did the people who wrote the answer really become RED? ?? When I looked it up, This article. @ other_user.password If you do it, you can't do it! So when I changed it to "password", it became RED. Then remove: admin from permit and the test is GREEN.

[10.4.2 destroy action exercise]

  1. Log in as an administrator user and try deleting a few sample users. What information does the Rails server log show when I delete a user? → You can see that the user with the corresponding ID is DELETEd from the database.

[10.4.3 User deletion test exercise]

  1. Try commenting out the admin user before filter in Listing 10.59 and see that the test result turns red. → It was RED safely.

Chapter 10 Summary

-Implemented edit, update, delete. -Display the user list with index. Implement pagination with gems. -Implement user management authority by assigning admin attribute. Now you can use admin? Which returns a logical value. -Execute a specific method before a specific action with befoure_action. (There is also after_action) -Friendly forwarding = Store the page request (GET only) that you wanted to go to in the session and redirect after logging in. After that, the stored session is deleted. -Create sample data (user) in db / seeds.rb.

Chapter 10 which had a certain volume is over. Now you have implemented all the basic functions. There are some situations where you have trouble with exercises, but there is nothing you can't understand if you look it up. Let's work calmly. Next next! Chapter 11! … Ah, an authentication function that uses an email address… (distant eyes). The reason for this will be explained in the following chapters.

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

A glossary that somehow captures the image

・ Forwarding To transfer something. Is friendly forwarding a "kind transfer"?

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 3]
(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 Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 6
(Ruby on Rails6) Creating data in a table
[Rails tutorial] A memorandum of "Chapter 11 Account Activation"
rails tutorial Chapter 7
rails tutorial Chapter 5
rails tutorial Chapter 10
rails tutorial Chapter 8
[Rails Tutorial Chapter 2] What to do when you make a mistake in the column name
Rails Tutorial Chapter 5 Notes
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