Rails Controllerを作成してアクションを実行するまでの手順

Rails Controllerを作成してアクションを実行するまでの手順

RailsでControllerを作成してアクションを実行するまでの手順を記述してます。

環境

  • OS windows10 pro 64bit
  • ruby 2.7.1
  • rails 6.0.3.2

※windows10にrubyをインストールして実行する手順はこちら
※windows10にRuby on Railsをインストールして利用する手順はこちら

Controller作成

まずは、下記のコマンドでcontroller「test」を作成します。

rails g controller test

「app\controller」に「test_controller.rb」が生成されます。

「test_controller.rb」を下記のとおりに編集して「show」アクションを追加します。

class TestController < ApplicationController
  def show
  end
end

次に「app\views\test」フォルダが作成されているので、ここに「show.html.erb」を下記の内容で作成します、

<h1>test/show</h1>

次にルーティングを設定するため、「config」ファルダ配下にある「routes.rb」を下記のように編集します。

Rails.application.routes.draw do
  get "test/show"
end

サーバーを起動します。

rails s

ブラウザから http://プライベートIP:3000/test/showにアクセスするとtest/showが表示されていることが確認できます。