Railsでは、URLから特定のコントローラとアクションを選ぶことを『ルーティング』と呼びます。
ルーティングの設定は、 /config/routes.rb で指定します。
こんな感じですね↓
アプリケーション名::Application.routes.draw do ルーティングを記述する実際に、アプリケーションに新しいactionを追加して、ルーティングの設定をしてみます。
end
routes.rb に以下を追加
この設定により、『/about』というパスでアクセスが来た時に、TopControllerのaboutアクションを呼び出すようになります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Study::Application.routes.draw do | |
root to: "top#index" | |
get "about" => "top#about", as: "about" # この行を追加 | |
end |
TopControllerにaboutアクションを追加
aboutアクションは特に何もしません。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
class TopController < ApplicationController | |
def index | |
@message = "こんにちは!" | |
end | |
def about # このアクションを追加 | |
end | |
end |
viewを作成
about.html.erbを作成します。ついでに、ちょっとインスタンス変数も使ってます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<% @page_title = "このサイトについて" %> | |
<h1><%= @page_title %></h1> | |
<p>このサイトはRailsの勉強をするサイトです。</p> |
サーバを起動
サーバを起動します。
rails server
ブラウザから、『http://localhost:3000/about』にアクセスしてみましょう。
こんな表示になればOKです。
0 件のコメント:
コメントを投稿