LoginSignup
3
4

More than 3 years have passed since last update.

【Rails】ルーティングの基礎的な書き方【Ruby】

Last updated at Posted at 2021-01-23

ルーティングの役割

railsガイド( https://railsguides.jp/routing.html )によると

Railsのルーターは受け取ったURLを認識し、適切なコントローラ内アクションやRackアプリケーションに割り当てます。

とのこと。

「route」を直訳すると「経路」ですから、リクエストの道案内役といったところでしょうか。

基礎的な書き方について記してみたいと思います。


基本の書き方
rootの指定
resourcesを用いた書き方


基本の書き方

HTTPリクエスト 'URIパターン', to: 'コントローラー名#アクション名'
もしくは
HTTPリクエスト 'URIパターン', controller: 'コントローラ名', action: 'アクション名'

Rails.application.routes.draw do
  get 'profile', to: 'users#show'
  post 'tweets', controller: 'tweets', action: 'create'
end

rootの指定

root(ルート)とは、Railsアプリを実行する上で基本となる場所(パス)のことです。
例えばローカル環境にてアプリを実行した時に、「 http://localhost:3000 」のURLを指定した際に遷移するページを設定することができます。
root to: 'コントローラー名#アクション名'
もしくは
root 'pages#main'

Rails.application.routes.draw do
  root to: 'pages#main'
  root 'pages#main'
end

resourcesを用いた書き方

resourcesメソッドを使用すると、index, new, create, edit, update, show, deleteの七つのアクションへの割り当てを自動的に行うことができます。

Rails.application.routes.draw do
  resources :articles
end

こちらは、以下の7行のルーティングと同義になります。

get    '/articles',          to: 'articles#index'
get    '/articles/:id',      to: 'articles#show'
get    '/articles/new',      to: 'articles#new
get    '/articles/:id/edit', to: 'articles#edit
post   '/articles',          to: 'articles#create
patch  '/articles/:id',      to: 'articles#update'
delete '/articles/:id',      to: 'articles#destroy'

参考文献

https://railsguides.jp/routing.html
https://web-camp.io/magazine/archives/16815

3
4
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
3
4