LoginSignup
0
0

More than 1 year has passed since last update.

Rails ルーティングについて備忘録

Posted at

Railsを使用したアプリケーションでは、HTTPリクエストをクライアントが送信したときに、ルーティングと呼ばれる作業が実行されます。ルーティングというのは、送信されたリクエストに対してどのコントローラを参照するのかを決める作業です。

例えば、以下のようなコードでルーティングが決定されます。

routes.rb
Rails.application.routes.draw do
  root 'static_pages#home' #参照するコントローラ名/アクション
  get  'static_pages/about' #URL
end

以下のコードでアプリケーションのルートURL(最初に表示するURL)を定義しています。

root 'static_pages#home'

また、'static_pages#home#`というのは、static_pagesコントローラのhomeアクションを参照するという意味です。

つまり、上記のコードは、「ルートURLにアクセスした時は、static_pagesコントローラのhomeアクションを実行する」という意味になります。

また、以下のコードでは、getリクエストで'static_pages/about'がリクエストされた時に,static_pagesコントローラのhomeアクションを実行するということを定義しています。

get  'static_pages/about'

ちなみに、static_pagesコントローラファイルは以下のように定義されています。

app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
  def home
  end

  def about
  end
end

homeアクションとaboutアクションが定義されているので、それぞれのアクションをしっかりと実行することができるようになっています。

他にもルーティングの定義の方法はありまして、例えば以下のような書き方をすることができます。

routes.rb
Rails.application.routes.draw do
  root 'static_pages#home'
  get  '/about',   to: 'static_pages#about'
end

この記法を行うことの利点は以下のとおりです。

  • about_path,about_urlという記述を使用することができるようになる。

about_path -> '/about'
about_url -> 'https://www.example.com/about'

これらはrootメソッドでルートURLを定義しているから使用できる記述になっています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0