KAEDE Hack blog

kaede0902 技術ブログ お仕事募集中。

Rails で routes.rb でルーティングをした

Puma starting in single mode...
* Version 4.3.6 (ruby 2.6.1-p33), codename: Mysterious Traveller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://127.0.0.1:3000
* Listening on tcp://[::1]:3000

f:id:kei_s_lifehack:20201017160655p:plain

Hello rails

guides.rubyonrails.org

rails generate controller Welcome index

Running via Spring preloader in process 80060
      create  app/controllers/welcome_controller.rb
       route  get 'welcome/index'
      invoke  erb
      create    app/views/welcome
      create    app/views/welcome/index.html.erb
      invoke  test_unit
      create    test/controllers/welcome_controller_test.rb
      invoke  helper
      create    app/helpers/welcome_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    scss
      create      app/assets/stylesheets/welcome.scss
  • view が作成された

Most important of these are of course the controller, located at app/controllers/welcome_controller.rb

and the view, located at

app/views/welcome/index.html.erb.

作成されたコントローラと view を確認

class WelcomeController < ApplicationController
  def index
  end
end
  • これが controllers/welcome_controller.rb
<h1>Welcome#index</h1>
<p>Find me in app/views/welcome/index.html.erb</p>
  • これが views/welcome/index.html.erb

ルーティングをする

guides.rubyonrails.org

Now that we have made the controller and view, we need to tell Rails when we want "Hello, Rails!" to show up. In our case, we want it to show up when we navigate to the root URL of our site, http://localhost:3000. At the moment, "Yay! You're on Rails!" is occupying that spot.

  • rails に route を教えないとさっきのページにはアクセスできない

  • config/routes.rb をかく

Rails.application.routes.draw do
  get 'welcome/index'
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
  • routes.rb はこうなっている

This is your application's routing file which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. Edit this file by adding the line of code root 'welcome#index'. It should look something like the following:

  • Domein 言語で書かれているらしい。
  • ここにルーティングを追加する
 root 'welcome#index'

f:id:kei_s_lifehack:20201017161721p:plain

  • これで welcome/index にアクセスするとさっきの view が見える

f:id:kei_s_lifehack:20201017161820p:plain

  • しかし welcome/ では出ない
  • 普通の index.html の仕様とは違う?