Rails Tutorial Chapter 10 Notes

It is a memorandum of Chapter 10.

table of contents

1 How to open a link in a new tab 2 How to send a PATCH request 3 Need to reload test 4 Password Exception Handling 5 Difference between authentication and authorization 6 Friendly Forwarding 7 Faker gem 8 Page Nation 9 How to output confirmation log

1 How to open a link in a new tab

If you want to open the clicked page in a new tab, add the target attribute as shown in the code below. Also, if only target =" _ blank " is used, phishing sites may be introduced, so it is necessary to add the rel =" noopener " attribute as shown in the code below.

app/views/users/edit.html.erb


    .
    .
    <div class="gravatar_edit">
      <%= gravatar_for @user %>
      <a href="https://gravatar.com/emails" target="_blank" rel="noopener">change</a>
    </div>
  </div>
</div>

2 How to send a PATCH request

If you write code using the form helper with edit as in the case of new, there are some differences from the time of new when you look at the HTML source.

<form accept-charset="UTF-8" action="/users/1" class="edit_user"
      id="edit_user_1" method="post">
  <input name="_method" type="hidden" value="patch" />
  .
  .
  .
</form>

First of all, since it is not possible to send a PATCH request with the Web browser as it is, the form is hidden bytype = "hidden"and PATCH is set there.

Also, Rails is new to users because it is automatically set to send PATCH requests at edit, even though form_with (@user) is exactly the same as at new. This is because the new_record? Logical value method distinguishes whether it is an existing user existing in the database.

When new, true is determined internally when existing, and POST or PATCH is automatically determined.

3 Need to reload test

The test code in this chapter introduces a new reload method. The place of use is the code below. By inserting this method, after refreshing the page, you can use the assert_equal``assert_select method to check if it has changed before and after the page was refreshed.

test/integration/users_edit_test.rb


require 'test_helper'
  .
  .
  test "successful edit" do
    get edit_user_path(@user)
    assert_template 'users/edit'
    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
    @user.reload                      #Refresh page
    assert_equal name,  @user.name
    assert_equal email, @user.email
  end
end

4 Password exception handling

When you want to edit only the name and image, if you do not enter the password without changing it, an error will occur in validation. Use the allow_nil: true option to validate an empty password when registering a new password and to operate normally without entering a password when editing.

app/models/user.rb


class User < ApplicationRecord
  .
  .
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
  .
end

By doing this, you can allow the password to be nil.

Also, since has_secure_password is designed to verify the existence only when the object is created, it is possible to eliminate the need to enter the password again when creating a new object and not allowing it to be empty.

5 Difference between authentication and authorization

--Authentication Identify users on your site. --Authorization To manage the operations that the user can perform. This time, it is managed so that only current_user can be edited.

6 Friendly forwarding

If a user who is not logged in tries to access the edit page, he / she will be skipped to the login page. It would be nice if you redirected to the variant page after logging in. Making the page that the user was trying to browse is called friendly forwarding.

When implementing, manage the page you were trying to open using session.

app/helpers/sessions_helper.rb


module SessionsHelper
  .
  .
  #Redirect to the memorized URL (or default value)
  def redirect_back_or(default)
    redirect_to(session[:forwarding_url] || default)
    session.delete(:forwarding_url)
  end

  #Remember the URL you tried to access
  def store_location
    session[:forwarding_url] = request.original_url if request.get?
  end
end

7 Faker gem If you want to create a sample user, you can easily create it by using Faker gem.

Normally it is only a development environment, but this time it will be used in all environments.

Gemfile


.
gem 'rails', '6.0.3'
gem 'bcrypt', '3.1.13'
gem 'faker', '2.1.2'
.
$ bundle install

db/seeds.rb


#1 main sample user
User.create!(name:  "Example User",
             email: "[email protected]",
             password:              "foobar",
             password_confirmation: "foobar")

#Additional users
99.times do |n|
  name  = Faker::Name.name
  email = "example-#{n+1}@railstutorial.org"
  password = "password"
  User.create!(name:  name,
               email: email,
               password:              password,
               password_confirmation: password)
end

Also, by using the create! method, an exception will be thrown instead of false when it fails, so you will not overlook the error.

$ rails db:migrate:reset
$ rails db:seed

8 page nation

If you want to use pagination, will_paginategem Use bootstrap-will_paginategem.

Gemfile


.
gem 'faker', '2.1.2'
gem 'will_paginate', '3.1.8'
gem 'bootstrap-will_paginate', '1.0.0'
.
.
$ bundle install

Write <% = will_paginate%> at the position you want to display

app/views/users/index.html.erb


<% provide(:title, 'All users') %>
<h1>All users</h1>

<%= will_paginate %>

<ul class="users">
  <% @users.each do |user| %>
    <li>
      <%= gravatar_for user, size: 50 %>
      <%= link_to user.name, user %>
    </li>
  <% end %>
</ul>

<%= will_paginate %>

Finally, change @ user = User.all during the index action to add page nations. Also, the : page parameter has an initial value of 1 and returns the first page. (30 per page by default)

app/controllers/users_controller.rb


 .
  def index
    @users = User.paginate(page: params[:page])
  end
  .
  .

9 How to put out the confirmation log

When deleting some data, if it is executed by pressing the button once, there is a risk that it will be deleted by mistake. Therefore, if you press the delete button, you can prevent it by displaying something like a confirmation log. It's very easy to set up, just add data: {confirm:" the string you want to display "}! !!

<%= link_to "delete", user, method: :delete,
            data: { confirm: "You suer?" }

Recommended Posts

Rails Tutorial Chapter 5 Notes
Rails Tutorial Chapter 10 Notes
Rails Tutorial Chapter 3 Notes
Rails Tutorial Chapter 4 Notes
Rails Tutorial Chapter 8 Notes
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 3 Learning
Rails Tutorial Memorandum (Chapter 3, 3.1)
Rails Tutorial Chapter 4 Learning
Rails Tutorial Chapter 1 Learning
Rails Tutorial Chapter 2 Learning
rails tutorial fighting notes Ⅲ
Rails Tutorial Memorandum (Chapter 3, 3.3.2)
rails tutorial
rails tutorial
rails tutorial
rails tutorial
[Rails Tutorial Chapter 4] Rails-flavored Ruby
rails tutorial
rails tutorial
rails tutorial
[Rails Struggle/Rails Tutorial] Summary of Rails Tutorial Chapter 2
[Rails Tutorial Chapter 5] Create a layout
rails tutorial chapter 10 summary (for self-learning)
Chewing Rails Tutorial [Chapter 2 Toy Application]
Rails Tutorial (4th Edition) Memo Chapter 6
Rails tutorial test
Rails tutorial memorandum 1
Rails tutorial memorandum 2
Start Rails Tutorial
[Beginner] Rails Tutorial
html & rails notes
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 9
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
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 6
Chapter 4 Rails Flavored Ruby
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 3
Rails Tutorial cheat sheet
Rails Tutorial Chapter 1 From Zero to Deployment [Try]
[Rails] Learning with Rails tutorial
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
Rails Tutorial 4th Edition: Chapter 1 From Zero to Deployment
Resolve ActiveRecord :: NoDatabaseError when doing rails test (Rails tutorial Chapter 3)
Ruby on Rails Tutorial Troublesome notes when running on Windows