web_bonsaiの日記

web開発の学習日記です。誰に見せるためでもないただの日記です。

Railsのrootページを設定する | Mac + Docker + Rails その0017

今日の環境

  • M1 Mac
  • macOS Monterey
  • Docker Desktop 4.8.x
  • Docker Compose v2.5.0
  • Rails 7

rails g controllerする

以下のコマンドを実行します。

docker-compose run --rm app bin/rails g controller homes index

以下のディレクトリとファイルが変更と新規作成されました。

new file:   rails/app/controllers/homes_controller.rb
new file:   rails/app/helpers/homes_helper.rb
new file:   rails/app/views/homes/index.html.erb
modified:   rails/config/routes.rb
new file:   rails/test/controllers/homes_controller_test.rb

これで https://localhost/homes/index にアクセスしたときに、views/homes/index.html.erbが表示されるようになりました。

rootにアクセスしたときにviews/homes/index.html.erbが表示されるように設定する

rails/config/routes.rb を開くと以下のようになっています。

Rails.application.routes.draw do
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  # root "articles#index"
end

一行追記して以下のようにします。

Rails.application.routes.draw do
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  # root "articles#index"

  root 'homes#index'
end

これで https://localhost にアクセスすると、views/homes/index.html.erbが表示されるようになりました。

routes.rbの記述ルール

root 'コントローラー名#アクション名' の記述ルールです。