[RUBY] rails tutorial Chapter 7


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 7 User Registration

7.1.2 Users resource

Display user information on a web application according to the custom of REST architecture.

What is REST?

REST refers to modeling the components that make up an application (such as users and microposts) as "resources." These resources support both Create / Read / Update / Delete (CRUD) operations on relational databases and four basic HTTP request methods (POST / GET / PATCH / DELETE). doing. Column 2.2 (rails tutorial Quoted from Chapter 2)

In other words, is it an image that uses the users model as a resource and supports both data (create, display, update, delete) operations and request methods (POST / GET / PATCH / DELETE)?

By doing so ・ Simplifies controller and action decisions (If it is a resource, it will be set automatically) · Dynamic web page creation (Display user information on a web application, etc.) Is it possible to realize?

When using the users model as a resource, use routing

resources :users

It seems to fill in.

7.2.2 Form HTML

I made a registration form for new users. I will supplement only the parts that were difficult to understand.

<%= form_with(model: @user, local: true) do |f| %>
    <%= f.label :name %>
    <%= f.text_field :name %>

    <%= f.label :email %>
    <%= f.email_field :email %>

    <%= f.label :password %>
    <%= f.password_field :password %>

    <%= f.label :password_confirmation, "Confirmation" %>
    <%= f.password_field :password_confirmation %>

    <%= f.submit "Create my account", class: "btn btn-primary" %>
<% end %>

form_with sends a “remote” XHR request by default, but here I want to send a regular “local” form request to almost certainly display the error message (7.3.3). (rails tutorial Quoted from Chapter 7)

What does it mean,,, What is “remote” XHR request ??

I looked it up. XHR seems to be something called Ajax. And ajax is asynchronous communication, and roughly speaking, it seems that you can change the display of a part of the page without page transition by js format request.

reference https://qiita.com/tambo/items/45211df065e0c037d032

In the rails tutorial, it seems that you want to send an html format request, that is, a normal local form request, to almost certainly display the error message. Why is the error message displayed uncertainly with a remote request? Well, I understand that the local request is sufficient for the sample_app I'm creating now.

As an aside, in form_tag and form_for before rails 5, it seems that the default was local form instead of remote form.

Next, I was ignorant about HTML form tags, so I looked it up.

Reference article ① http://www.htmq.com/html5/form.shtml A rough description of form tags.

Reference article ② https://developer.mozilla.org/ja/docs/Learn/Forms/How_to_structure_an_HTML_form The label is also written.

The block variable (f) calls the method that generates the input tag for the attribute of the object (@user in this case) passed as the first argument of form_with.

reference https://rakuda3desu.net/rakudas-rails-tutorial7-2/

Rails knows that @ user's class is User. Also, since @user is a new user, Rails decides that the form should be built using the post method. (rails tutorial Quoted from Chapter 7)]

I investigated what this part means.

Reference article ① https://qiita.com/hmmrjn/items/24f3b8eade206ace17e2 It seems that if there is a related model and @user exists in the DB, it jumps to the update action, otherwise it jumps to the create action.

Reference article ② https://pikawaka.com/rails/form_with This article was also easy to understand.

If the instance created by the controller is newly created by the new method and has no information, it is automatically created by the create method, and if it already has the information, it is automatically created by the update action. It will sort it out. (Quoted from the above article)

I think I understood it very well ...

7.3.1 Correct form

params contains hashes (hash-of-hashes: nested hashes) for multiple hashes. In the debug information, the result of the form submission is stored in the user hash along with the attributes corresponding to the submitted value. The key of this hash will be the value of the name attribute that was in the input tag. For example:

<input id="user_email" name="user[email]" type="email" />

The value "user [email]" matches the value of the: email key in the user hash. (rails tutorial Quoted from Chapter 7)]

An important point here !!

7.3.2 Strong Parameters

params.require(:user).permit(:name, :email, :password, :password_confirmation)

What is the require method? Specify the parameter group to receive

What is the permit method? Specify available parameter names

reference https://techacademy.jp/magazine/22078

7.3.4 Test on failure

Exercise 1 An error has occurred !!


#Listing 7.25:Template for testing error messages
require 'test_helper'
class UsersSignupTest < ActionDispatch::IntegrationTest

  test "invalid signup information" do
    get signup_path
    assert_no_difference 'User.count' do
      post users_path, params: { user: { name:  "",
                                         email: "[email protected]",
                                         password:              "foo",
                                         password_confirmation: "bar" } }
    assert_template 'users/new'
    assert_select 'div#<CSS id for error explanation>'
    assert_select 'div.<CSS class for field with error>'

After writing Listing 7.25 and doing a test

ERROR["test_invalid_signup_information", #<Minitest::Reporters::Suite:0x000000000adddc40 @name="UsersSignupTest">, 0.3698949000099674]
 test_invalid_signup_information#UsersSignupTest (0.37s)
Nokogiri::CSS::SyntaxError:         Nokogiri::CSS::SyntaxError: unexpected '#' after '[#<Nokogiri::CSS::Node:0x000000000addfc70 @type=:ELEMENT_NAME, @value=["div"]>]'
            test/integration/users_signup_test.rb:13:in `block in <class:UsersSignupTest>'

And the error,

Listing 7.25 has been added

assert_select 'div#<CSS id for error explanation>'
assert_select 'div.<CSS class for field with error>'

These are the above two sentences.

<CSS id for error explanation>

Ah. .. .. Only hints are written here, and you have to write the id yourself ... So

assert_select 'div#error_explanation'
assert_select 'div.field_with_errors'

I fixed it.

7.4.1 Completion of registration form


#Listing 7.26:User's create action to save and redirect
class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to @user
      render 'new'


    def user_params
      params.require(:user).permit(:name, :email, :password,

redirect_to @user

I can understand the meaning of the above code, but I referred to it because there is an article that describes it in detail.

reference https://qiita.com/Kawanji01/items/96fff507ed2f75403ecb

However, according to Tutorial 5.3.2, Rails conventions basically use relative paths for links, but absolute paths for redirect links. (Quoted from the above article)

Was that so? When you look up

The Rails tutorial follows the general conventions, basically using the _path format and using the _url format only for redirects. This is because the HTTP standard requires a full URL when redirecting. (rails tutorial Quoted from Chapter 5)]

It was true ...

7.4.3 Actual user registration

a problem occured!! To reset the database

rails db:migrate:reset

Execute. But it cannot be reset.

ermission denied @ apply2files - C:/environment/sample_app/db/development.sqlite3
Couldn't drop database 'db/development.sqlite3'
rails aborted!
Errno::EACCES: Permission denied @ apply2files - C:/Users/81801/environment/sample_app/db/development.sqlite3
bin/rails:4:in `require'
bin/rails:4:in `<main>'
Tasks: TOP => db:drop:_unsafe
(See full trace by running task with --trace)

Solution I solved it by referring to the following article. https://teratail.com/questions/67393 https://qiita.com/Toshiki23/items/f366504844fd22ad87d9

Apparently using sqlite3 for the database on windows rails drop command rails db: reset command rails db: migrate: reset command There seems to be a problem with. Alas windows ...

Manually delete the db / development.sqlite3 file from the editor explorer as described in the article (because the rm command was not followed at the command prompt),

rails db:create db:migrate

When I executed it again

Database 'db/development.sqlite3' already exists
Database 'db/test.sqlite3' already exists

That? It should have been erased, but it remains ... The development.sqlite3 file has certainly disappeared from the editor I'm using ...

,,,,What should I do! !! !! !! !! I searched for the whereabouts of the deleted development.sqlite3 file for the time being.

reference https://maitakeramen.hatenablog.com/entry/2018/02/08/131755

I can't find it for some reason when I look for the trash can ... (Is it because it hasn't been deleted ??)

I looked for it, and when I looked in the sample_app / db directory from windows explorer, I found the development.sqlite3 file !!

For the time being, I copied it to the db directory of the open editor.

When I took a peek at the data with DB Browser for SQlite, the data in the users table was empty.

I tried to find out the cause, but I didn't understand. For the time being, we have achieved the database reset and will move on to the next ...

Digression After this, I was told that if I use Git Bash, I can also use Linux commands, and after that I decided to use that as well for learning.

7.4.4 Successful test

Exercise 2 I was able to clear the exercise without any problems, but I searched for the content_tag helper. content_tag helper content_tag (: element name, content to be displayed, option)

reference https://techacademy.jp/magazine/42167

At the end

The content suddenly became difficult. It was also difficult to understand concepts like the User resource that were commonly used in the tutorial. I couldn't understand how to generate a form using the form_with helper at one time, so I read it back several times. I often encountered errors and it took a long time.

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 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)
rails tutorial
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 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
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
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)
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)