[RUBY] Rails Tutorial 6th Edition Learning Summary Chapter 3

Overview

This article deepens my understanding by writing a Rails tutorial commentary article to further solidify my knowledge It is part of my study. In rare cases, ridiculous content or incorrect content may be written. Please note. I would appreciate it if you could tell me implicitly ...

Source Rails Tutorial

What to do from now on

We will comprehensively learn how to create a Rails application by creating a Twitter-like sample application Sample_app. This chapter starts by creating a new project Sample_app.

I wrote articles in quite detail up to Chapter 2, but after Chapter 3 The amount of code will increase considerably, so what you can do by reading the Rails tutorial I'll abbreviate it ...

setup

Initial setting

Create a new Sample_app Update the Gemfile. Don't forget --without production because you don't want to install the production pg gem again this time. Since it is a new application, initialize the Git repository. Rewrite the README here as well. After rewriting the README, commit it for the time being. Also create a remote repository for Sample_app on Github. After creating a remote repository, push it In case of Cloud9 environment, edit development.rb so that the application can be started locally. For the time being, just add the code for hello and world display as in Chapter 2 and push it to heroku.

Exercise
  1. The README is automatically displayed at the bottom of the top page of the Github repository. Of course you can open the file and look directly image.png
  2. You can see that hello, world! Is displayed. image.png Trivia here You can check the domain name of the app deployed on heroku with `heroku domains`.

Static page

As a development habit, instead of always working on the master branch, create a topic branch each time you implement something It is said that it is a good habit to work. By doing so, it is easy to divide the work. Easy to see the work There are various advantages. From this time on, I will create a topic branch and work on it.

$ git checkout -b static-pages
Static page generation

I will create it from the controller for static pages at once

$ rails g controller StaticPages home help 

generate may be the abbreviation g There are other abbreviations, and it's a good idea to remember them.

Complete command Shortened form
$ rails server $ rails s
$ rails console $ rails c
$ rails generate $ rails g
$ rails test $ rails t
$ bundle install $ bundle

From Rails Tutorial 6th Edition https://railstutorial.jp/chapters/static_pages?version=6.0#table-shortcuts

For now, push the static-pages branch remotely Setting origin to static-pages upstream with the -u option After that, you can do the same push with just git push.

When the controller is automatically generated by the generate command, the routes.rb file is also automatically updated. In this case, I created a home action and a help action with generate.

routes.rb


Rails.application.routes.draw do
  get 'static_pages/home'
  get 'static_pages/help'
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
  root "application#hello"
end

The routing rules for the home and help actions are set automatically. Start up the local server and display the home page of static_pages. image.png

Rails will refer to the router when you specify the URL (this time / static_pages / home) Perform the action of the corresponding controller. (Home action of StaticPages controller) After that, the view corresponding to the action is output. The static page controller doesn't change content each time, so the action is empty (same page content).

Exercise
$ rails g controller Foo bar baz
  1. The abbreviation d can be used for destroy.
$ rails d controller Foo

Static page adjustment

The home page and help page created in the current state are completed in HTML and are completely static pages. In other words, it is a page that can be edited without knowledge of Rails. Here, as in Chapter 2, you can get user data or post data according to the content. Rails knowledge (ERB) is required for actions that change the display content (dynamic).

Start with a test

First test

Before adding the about page, write a test for the about page in advance. Since the generate command automatically generates tests for the home and help pages First of all, run a test to confirm that there is no problem at this time

$ rails t

...

Finished in 6.708000s, 0.2982 runs/s, 0.2982 assertions/s.
2 runs, 2 assertions, 0 failures, 0 errors, 0 skips

Red The Test Driven Development (TDD) cycle Write tests that fail (tests for unimplemented features, etc.) → Fail (RED) Write the actual application code and pass the test written earlier → Success (GREEN) 3 steps of refactoring (REFACTOR)

Based on this, I will write a test of the About page that I have not made yet

static_pages_controller_test.rb


require 'test_helper'

class StaticPagesControllerTest < ActionDispatch::IntegrationTest
  
  ...
  
  test "should get about" do
    get static_pages_about_url
    assert_response :success
  end
end

This code sends a GET request to the about page of static_pages I am testing the content that the response code is 200 OK (success).

Of course, I haven't implemented any About page yet, so I get the error as expected.

Green Take a look at the error message

Error:
StaticPagesControllerTest#test_should_get_about:
NameError: undefined local variable or method `static_pages_about_url' for #<StaticPagesControllerTest:0x000055b65cfc03b0>
    test/controllers/static_pages_controller_test.rb:15:in `block in <class:StaticPagesControllerTest>'

If you read it in detail In StaticPagesControllerTest should_get_about No method is defined for static_pages_about_url (there is no URL for About) Is angry.

This is because I haven't set up routing

Let's add routing at once. in routes.rb get 'static_pages/about'To add. Adding a route enables a helper called static_pages_about_url.

If you run the test again, this time

Error:
StaticPagesControllerTest#test_should_get_about:
AbstractController::ActionNotFound: The action 'about' could not be found for StaticPagesController
    test/controllers/static_pages_controller_test.rb:15:in `block in <class:StaticPagesControllerTest>'

This is also a simple error I'm angry that I can't find the about action. This is the result of adding routing to refer to the about action of the static_pages controller.

Let's add an About action right away

  def about 
  end

Just write this inside the static_pages controller The content of the action is still a completely static page like home and help, so empty is OK

If you run the test with this, this time

Error:
StaticPagesControllerTest#test_should_get_about:
ActionController::MissingExactTemplate: StaticPagesController#about is missing a template for request formats: text/html
    test/controllers/static_pages_controller_test.rb:15:in `block in <class:StaticPagesControllerTest>'

This is angry that the about template (view) cannot be found.

This is also supported by adding a view. Add about.html.erb in app / views / static_pages.

The test succeeds (GREEN) in this state

Finished in 0.976764s, 3.0714 runs/s, 3.0714 assertions/s.
3 runs, 3 assertions, 0 failures, 0 errors, 0 skips

A slightly dynamic page

Change the title dynamically. Disable layout for study

$ mv app/views/layouts/application.html.erb layout_file

This command temporarily renames and moves the layout file application.html.erb to disable it.

Write the title test first The title should change from page to page, so the code looks like this.

  test "should get home" do
    get static_pages_home_url
    assert_response :success
    assert_select "title", "Home | Ruby on Rails Tutorial Sample App"
  end

  test "should get help" do
    get static_pages_help_url
    assert_response :success
    assert_select "title", "Help | Ruby on Rails Tutorial Sample App"
  end
  
  test "should get about" do
    get static_pages_about_url
    assert_response :success
    assert_select "title", "About | Ruby on Rails Tutorial Sample App"
  end

Select the title tag and make sure that its contents match. Of course, the test is RED because it is not implemented

First, rewrite the view of the home, help, about page.

Since I set a title for each page, the test will be GREEN.

Finished in 0.062407s, 48.0717 runs/s, 96.1433 assertions/s.
3 runs, 6 assertions, 0 failures, 0 errors, 0 skips

Exercise

  1. You can expand the variable by enclosing the variable with # {} in the part (character string) enclosed in double quotation marks. This time, the string Ruby on Rails Tutorial Sample App is assigned to the variable, so that string is expanded. Substituting variables for common parts and making it possible to flexibly respond to changes is a basic matter that does not change in any program language.
  def setup
    @base_title = "Ruby on Rails Tutorial Sample App"
  end
  test "should get home" do
    get static_pages_home_url
    assert_response :success
    assert_select "title", "Home | #{@base_title}"
  end

  test "should get help" do
    get static_pages_help_url
    assert_response :success
    assert_select "title", "Help | #{@base_title}"
  end
  
  test "should get about" do
    get static_pages_about_url
    assert_response :success
    assert_select "title", "About | #{@base_title}"
  end

Layout and embedding Ruby

At this stage, most of the HTML structure (basic tags such as head) is duplicated on all home, help, and about pages. The title is also the same for the Ruby on Rails Tutorial Sample App. It is important to remove such duplication and DRY.

provide method in view

symbol,"String")By specifying


 You can call the string associated with the symbol with yield.
 Ruby code can be used in views
 The view is embedded Ruby [ERB (Embedded RuBy)] is a file in the format that allows you to embed Ruby in HTML.
 Enclose it in <%%> and just execute the statement inside
 The difference is that if you enclose it in <% =%>, the statement inside will be executed and the result will be inserted into the template.

 Here is the result of rewriting the title part using this mechanism

```erb
<% provide(:title,"Help") %>
<!DOCTYPE html>
<html>
  <head>
    <title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
  </head>

Of course, the test also passes.

If this is left as it is, common parts will remain, so I will refactor it immediately. First, enable the layout file that you disabled earlier

mv layout_file app/views/layouts/application.html.erb

Then, replace the title tags individually placed in home, help, and about with the title tags of the layout file.

erb:application.html.erb


<!DOCTYPE html>
<html>
  <head>
    <title><%= yield(:title)%> | Ruby on Rails Tutorial Sample App</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

The contents of the view of each page are substituted as they are in the yield part. In other words, what is displayed when trying to display each page It is application.html.erb that loaded the view of each page.

After that, extra things such as html tags are left in the view of each page, and as it is, application.html.erb Since it will be duplicated, delete unnecessary parts and make the view of each page only the content.

erb:help.html.erb


<% provide(:title,"Help") %>
<h1>Help</h1>
<p>
  Get help on the Ruby on Rails Tutorial at the
  <a href="https://railstutorial.jp/help">Rails Tutorial help page</a>.
  To get help on this sample app, see the
  <a href="https://railstutorial.jp/#ebook"><em>Ruby on Rails Tutorial</em>
  book</a>.
</p>
Exercise
  1. Write the Contact test first (TDD)

static_pages_controller_test.rb


 
  test "should get contact" do
    get static_pages_contact_url
    assert_response :success
    assert_select "title", "Contact | #{@base_title}"
  end

After that, add the contact routing to routes.rb and Add a contact action to static_pages_controller and Just create a contact view.

Finished in 1.044651s, 3.8290 runs/s, 7.6581 assertions/s.
4 runs, 8 assertions, 0 failures, 0 errors, 0 skips

The test also passes.

Routing settings

For the time being, I set the hello action to display hello, world in the root URL to deploy. I made a home page this time, so I will move it there root 'static_pages/home'

Exercise

static_pages_controller_test.rb


  test "should get root" do
    get root_url
    assert_response :success
  end
  1. Ruby can comment out the line by adding # at the beginning of the line By the way, Windows can comment out that line with CTRL + /. Comment out the root URL. `` `# root'static_pages # home'```
Error:
StaticPagesControllerTest#test_should_get_root:
NameError: undefined local variable or method `root_url' for #<StaticPagesControllerTest:0x000055d85cb31200>
    test/controllers/static_pages_controller_test.rb:10:in `block in <class:StaticPagesControllerTest>'

I got an error if the root_url method was not defined.

You can see that the root_url helper can be used by setting the rootURL.

Summary of this chapter

Since the work of Chapter 3 has been completed Commit If you run the test when deploying, you won't have to worry about finding bugs after deploying.

← To the previous chapter

To the next chapter →

Recommended Posts

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 6th Edition Learning Summary Chapter 3
Rails Tutorial 6th Edition Learning Summary Chapter 8
Rails Tutorial (4th Edition) Memo Chapter 6
Rails Tutorial Chapter 3 Learning
Rails Tutorial Chapter 4 Learning
Rails Tutorial Chapter 1 Learning
Rails Tutorial 4th Edition: Chapter 1 From Zero to Deployment
[Rails Struggle/Rails Tutorial] Summary of Rails Tutorial Chapter 2
rails tutorial chapter 10 summary (for self-learning)
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 0: Preliminary Basic Knowledge Learning 5
Rails tutorial (6th edition) Follow/unfollow background operation
Rails Tutorial Chapter 10 Notes
Rails Tutorial Chapter 3 Notes
[Rails] Learning with Rails tutorial
Rails Tutorial Memorandum (Chapter 3, 3.1)
Rails Tutorial Chapter 4 Notes
Rails Tutorial Chapter 8 Notes
Rails Tutorial Memorandum (Chapter 3, 3.3.2)
[Rails Tutorial Chapter 4] Rails-flavored Ruby
Rails tutorial (6th edition) Background operation of login function
Rails tutorial (6th edition) Background operation of password reset function
[Rails Tutorial Chapter 5] Create a layout
Chewing Rails Tutorial [Chapter 2 Toy Application]
rails tutorial
rails tutorial
rails tutorial
rails tutorial
Rails Tutorial (6th Edition) -Explanation of background operation for each function-
rails tutorial
rails tutorial
rails tutorial
Rails tutorial (6th edition) Background operation of the posting function of the micro post
A summary of only Rails tutorial setup related
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 6
Rails tutorial test
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 3
[Ruby on Rails] Rails tutorial Chapter 14 Summary of how to implement the status feed
Rails tutorial memorandum 1
Rails Tutorial Chapter 1 From Zero to Deployment [Try]
Rails learning day 3
Rails 6.0 Routing Summary
Rails learning day 2
Start Rails Tutorial
rails db: 〇〇 Summary
[Beginner] Rails Tutorial
[Learning Memo] Metaprogramming Ruby 2nd Edition: Chapter 3: Methods
rails learning day 1