4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[早見表付]ルーティングの方法まとめ

Last updated at Posted at 2023-05-01

はじめに

ルーティングを編集するにあたり、「こんなパスを作れたらいいけれど、どうやって書けばいいのだろう?」と毎度迷ってしまい、都度調べていました。
自分の中での整理もできるように、ルーティング方法をまとめておきます。

こんな方ぜひ読んでいただきたい

  • ルーティングとはそもそもなに?
  • ルーティングの書き方が知りたい!
  • ルーティングについて簡単に勉強はしたけど、書き方を覚えていない
  • ルーティングについて詳しいけど、どれを使うかド忘れした!
  • こんなパスで設定してみたいけど、どうやれば良いんだろう?

[結論]早見表

「こんなパスを作りたい!」の結論を先にまとめておきます。
逆引き(作りたいバスから検索)することもできると思います。

ルーティングの大まかな書き方はわかっているけど、どれを使えば良いか忘れてしまったときなどにお使いください。
書き方もわからないよ、という方はページを進んでいくと詳しく記載をしています。

また、パスはuserpostadminを使って表していますが、全て変更可能ですので、適宜調整してください。

"/user" [users#show,create...]

resource

config/routes.rb
Rails.application.routes.draw do
    resource :user do
end

"/users" [users#index...]
"/users/:id" [users#show,create...]

resources

config/routes.rb
Rails.application.routes.draw do
    resources :users do
end

"/user/post" [posts#show,create...]

resource + resource

config/routes.rb
Rails.application.routes.draw do
    resource :user do
        resource :post
    end
end

"/users/:user_id/post" [posts#show...]

resources + resource

config/routes.rb
Rails.application.routes.draw do
    resources :users do
        resource :post
    end
end

"/user/posts" [posts#index...]
"/user/posts/:id" [posts#show,create...]

resource + resources

config/routes.rb
Rails.application.routes.draw do
    resource :user do
        resources :posts
    end
end

"/users/:user_id/posts" [posts#index...]
"/users/:user_id/posts/:id" [posts#show,create...]

resources + resources

config/routes.rb
Rails.application.routes.draw do
    resources :users do
        resources :posts
    end
end

"/admin/users" [admin/users#index...]
"/admin/users/:id" [admin/users#show,create...]

(特定のディレクトリ下(ここではadmin下)にコントローラを入れたい場合)

namespace + resources

config/routes.rb
Rails.application.routes.draw do
    namespace :admin do
        resources :users
    end
end

"/users" [admin/users#index...]
"/users/:id" [admin/users#show,create...]

(パスには反映させたくないが、特定のディレクトリ下(ここではadmin下)にコントローラを入れたい場合)

module + resources

config/routes.rb
Rails.application.routes.draw do
    scope module: :admin do
        resources :users
    end
end

"/users/followers" [users#followers]

(resourcesで自動設定されるアクション以外を、idを含めず追加したい場合)

collection + get,post,put,patch,delete

config/routes.rb
Rails.application.routes.draw do
    resources :users do
        collection do
            get :followers
        end
    end
end

"/users/:id/followers" [users#followers]

(resourcesで自動設定されるアクション以外を、idを含めて追加したい場合)

member + get,post,put,patch,delete

config/routes.rb
Rails.application.routes.draw do
    resources :users do
        member do
            get :followers
        end
    end
end

そもそもルート・ルーティングとは

ルーティングの目的は、Railsガイドに以下のように記載があります。

Railsのルーターは受け取ったURLを認識し、適切なコントローラ内アクションやRackアプリケーションに振り分けます。ルーターはパスやURLも生成できるので、ビューでこれらのパスやURLを直接ハードコードする必要はありません。
(https://railsguides.jp/routing.html)

ルーティングで、URL(パス)を認識してくれるようになり、コントローラのアクションを振り分けてくれます。
まとめて記載することで、各ビューに直接コーディングする必要がなくなります。

ルーティングの基本

ルーティングの書き方

ルーティングの書き方は以下です。

config/routes.rb
Rails.application.routes.draw do
    get '/users', to: 'users#index'
    get '/users', :controller => 'users', :action => 'index'
    get '/users' => "users#index"
end

先頭にHTTPメソッド(get)を記述し、次にパス(/users)、後にコントローラー(users)とメソッド(index)を記述します。

上記では3つの書き方がありますが、どれでも問題ないのでどれか1つを使用します。
他にも書き方は複数あります。

HTTPメソッドは
GET (既存データを取得しページを表示するなどしたいとき),
POST (新規データを作成したいとき),
PUT (既存データを更新したいとき),
PATCH (既存データとの差分を更新したいとき),
DELETE (既存データを削除したいとき)
が使用できます。

この書き方で自由にルーティングを設定することができますが、Railsが用意してくれているメソッドを使えば、より簡単にルーティングを定義することができます。
そのメソッドを以下で紹介します。

root

最も基本となるルートのルーティング方法です。

config/routes.rb
Rails.application.routes.draw do
    root 'statics#hello'
end

ローカル環境でサーバーを起動(rails server)し、localhost:3000のページがルートです。

resources (複数形)

上記の基本の書き方でルーティングを記述していくことも可能ですが、煩雑になってしまうので、たった1行で簡単に複数のルーティングを自動設定できる方法がresourcesです。

書き方はとても簡単で、

config/routes.rb
Rails.application.routes.draw do
    resources :users
end

これだけです。
これで、index, create, new, edit, show, update, destroy アクションが自動で設定されます。

     users GET    /users(.:format)                       users#index
           POST   /users(.:format)                       users#create
  new_user GET    /users/new(.:format)                   users#new
 edit_user GET    /users/:id/edit(.:format)              users#edit
      user GET    /users/:id(.:format)                   users#show
           PATCH  /users/:id(.:format)                   users#update
           PUT    /users/:id(.:format)                   users#update
           DELETE /users/:id(.:format)                   users#destroy

resource (単数形)

上記ではresourcesと複数形でしたが、resourceと単数形でも書くことができます。

config/routes.rb
Rails.application.routes.draw do
    resource :user
end

この場合、パスは以下のように設定されます。

           POST   /user(.:format)                   users#create
  new_user GET    /user/new(.:format)               users#new
 edit_user GET    /user/edit(.:format)              users#edit
      user GET    /user(.:format)                   users#show
           PATCH  /user(.:format)                   users#update
           PUT    /user(.:format)                   users#update
           DELETE /user(.:format)                   users#destroy

単数形にすることで
パスに:idが含まれなくなり、indexアクションも無くなりました。
パスのuserは単数形ですが、コントローラーはusersのままなので注意してください。

ネスト

ネストさせることで、関連のあるモデルのパスをまとめて作成することが可能です。

config/routes.rb
Rails.application.routes.draw do
    resources :users do
        resources :posts
    end
end

resourcesresourceを掛け合わせることで、idの有無を分けることができます。

実際にできるパスは以下で紹介します。

resources(複数形) & resources(複数形)

config/routes.rb
Rails.application.routes.draw do
    resources :users do
        resources :posts
    end
end

この場合、パスは以下のように設定されます。

     user_posts GET    /users/:user_id/posts(.:format)                  posts#index
                POST   /users/:user_id/posts(.:format)                  posts#create
  new_user_post GET    /users/:user_id/posts/new(.:format)              posts#new
 edit_user_post GET    /users/:user_id/posts/:id/edit(.:format)         posts#edit
      user_post GET    /users/:user_id/posts/:id(.:format)              posts#show
                PATCH  /users/:user_id/posts/:id(.:format)              posts#update
                PUT    /users/:user_id/posts/:id(.:format)              posts#update
                DELETE /users/:user_id/posts/:id(.:format)              posts#destroy
          users GET    /users(.:format)                                 users#index
                POST   /users(.:format)                                 users#create
       new_user GET    /users/new(.:format)                             users#new
      edit_user GET    /users/:id/edit(.:format)                        users#edit
           user GET    /users/:id(.:format)                             users#show
                PATCH  /users/:id(.:format)                             users#update
                PUT    /users/:id(.:format)                             users#update
                DELETE /users/:id(.:format)                             users#destroy

resourcesと複数形にしたusers側にも、post側にもidが付きます。

特定の user が複数の post を持っているとき、
つまり1人のユーザーが、投稿(post)を複数持てる時に使いやすい方法です。

resources(複数形) & resource(単数形)

config/routes.rb
Rails.application.routes.draw do
    resources :users do
        resource :post
    end
end

この場合、パスは以下のように設定されます。

  new_user_post GET    /users/:user_id/post/new(.:format)               posts#new
 edit_user_post GET    /users/:user_id/post/edit(.:format)              posts#edit
      user_post GET    /users/:user_id/post(.:format)                   posts#show
                PATCH  /users/:user_id/post(.:format)                   posts#update
                PUT    /users/:user_id/post(.:format)                   posts#update
                DELETE /users/:user_id/post(.:format)                   posts#destroy
                POST   /users/:user_id/post(.:format)                   posts#create
          users GET    /users(.:format)                                 users#index
                POST   /users(.:format)                                 users#create
       new_user GET    /users/new(.:format)                             users#new
      edit_user GET    /users/:id/edit(.:format)                        users#edit
           user GET    /users/:id(.:format)                             users#show
                PATCH  /users/:id(.:format)                             users#update
                PUT    /users/:id(.:format)                             users#update
                DELETE /users/:id(.:format)                             users#destroy

resourcesと複数形にしたusers側にはidが付き、
resourceと単数形にしたpost側にはidが付きません。

特定の user が限定の post を持っているとき、
つまり1人のユーザーが、投稿(post)を1つしか持てない時に使いやすい方法です。

上記以外にもresources複数形とresourceは組み合わせ自由なので、idが必要かどうかで判断して使います。

少し応用

namespace

パスをグループ化したい時に使うのがnamespaceです。

例えば、管理者目線から見たユーザーフォルダを作成したいときなどに有効です。

config/routes.rb
Rails.application.routes.draw do
    namespace :admin do
        resources :users
    end
end

この場合、パスは以下のように設定されます。

    admin_users GET    /admin/users(.:format)                           admin/users#index
                POST   /admin/users(.:format)                           admin/users#create
 new_admin_user GET    /admin/users/new(.:format)                       admin/users#new
edit_admin_user GET    /admin/users/:id/edit(.:format)                  admin/users#edit
     admin_user GET    /admin/users/:id(.:format)                       admin/users#show
                PATCH  /admin/users/:id(.:format)                       admin/users#update
                PUT    /admin/users/:id(.:format)                       admin/users#update
                DELETE /admin/users/:id(.:format)                       admin/users#destroy

上記では、namespaceの中でresourcesを使用していますが、resourceはもちろん、getなども使用可能です。

module

別のディレクトリにコントローラをまとめたいときに使うのがmoduleです。
namespaceと似ていますが、パスの設定が違います。

namespaceと同じく、管理者目線から見たユーザーフォルダを作成したいときに有効ですが、moduleの場合はパスにそれを表示させたくないときに使います。

実際に作成されるパスを見てみると分かりやすいです。

config/routes.rb
Rails.application.routes.draw do
    scope module: :admin do
        resources :users
    end
end

この場合、パスは以下のように設定されます。

    users GET    /users(.:format)                           admin/users#index
          POST   /users(.:format)                           admin/users#create
 new_user GET    /users/new(.:format)                       admin/users#new
edit_user GET    /users/:id/edit(.:format)                  admin/users#edit
     user GET    /users/:id(.:format)                       admin/users#show
          PATCH  /users/:id(.:format)                       admin/users#update
          PUT    /users/:id(.:format)                       admin/users#update
          DELETE /users/:id(.:format)                       admin/users#destroy

adminは コントローラ#アクション の中だけに追加されます。
パスには表示したくないときに有効です。

上記では、namespaceの中でresourcesを使用していますが、resourceはもちろん、getなども使用可能です。

collection

ルーティングを追加したいときに使うのがcollectionです。

resourcesresourceで自動作成されるアクション以外が必要なときに有効です。

config/routes.rb
Rails.application.routes.draw do
    resources :users do
        collection do
            get :followers
        end
    end
end

この場合、パスは以下のように設定されます。

          users GET    /users(.:format)                       users#index
                POST   /users(.:format)                       users#create
       new_user GET    /users/new(.:format)                   users#new
      edit_user GET    /users/:id/edit(.:format)              users#edit
           user GET    /users/:id(.:format)                   users#show
                PATCH  /users/:id(.:format)                   users#update
                PUT    /users/:id(.:format)                   users#update
                DELETE /users/:id(.:format)                   users#destroy
----- 以下がcollectionによるルーティングの追加部分 -----
followers_users GET    /users/folowers(.:format)              users#followers    

member

ルーティングを追加したいときに使うのがmemberです。

collectionと同じく、
resourcesresourceで自動作成されるアクション以外が必要なときに有効ですが、
collectionにはidが付かず、memberにはidが付きます。

config/routes.rb
Rails.application.routes.draw do
    resources :users do
        member do
            get :followers
        end
    end
end

この場合、パスは以下のように設定されます。

          users GET    /users(.:format)                       users#index
                POST   /users(.:format)                       users#create
       new_user GET    /users/new(.:format)                   users#new
      edit_user GET    /users/:id/edit(.:format)              users#edit
           user GET    /users/:id(.:format)                   users#show
                PATCH  /users/:id(.:format)                   users#update
                PUT    /users/:id(.:format)                   users#update
                DELETE /users/:id(.:format)                   users#destroy
----- 以下がmemberによるルーティングの追加部分 -----
 followers_user GET    /users/:id/folowers(.:format)          users#followers    

memberは省略も可能です。
省略した場合の記載方法は以下です。

config/routes.rb
Rails.application.routes.draw do
    resources :users do
        get :followers
    end
end

ルーティングのオプション

as

ルーティングに別名をつけることもできます。

config/routes.rb
Rails.application.routes.draw do
    get '/login', to: 'users#new', as: 'signin'
end

この場合、パスは以下のように設定されます。

sign_in GET    /login(.:format)          users#new    

only

resourcesresource で作成されるアクションを限定することが可能です。

onlyで指定したアクションのみ作成されます。

config/routes.rb
Rails.application.routes.draw do
    resources :users, only: [:index, :create, :show]
end

この場合、パスは以下のように設定されます。

     users GET    /users(.:format)                       users#index
           POST   /users(.:format)                       users#create
      user GET    /users/:id(.:format)                   users#show

もちろん、onlyで指定するものは自由です。

except

同じく、resourcesresource で作成されるアクションを限定します。

ただしonlyとは逆でexceptで指定したアクション以外が作成されます。

config/routes.rb
Rails.application.routes.draw do
    resources :users, except: [:index, :create, :show]
end

この場合、パスは以下のように設定されます。

  new_user GET    /users/new(.:format)                   users#new
 edit_user GET    /users/:id/edit(.:format)              users#edit
           PATCH  /users/:id(.:format)                   users#update
           PUT    /users/:id(.:format)                   users#update
           DELETE /users/:id(.:format)                   users#destroy

もちろん、exceptで指定するものは自由です。

終わりに

ルーティングをまとめてみました。
間違いや、「この方法使いやすいよ!」というものがあれば是非ご教授ください。

お読みいただき、ありがとうございました!

参考

https://techracho.bpsinc.jp/baba/2020_11_20/15619
https://autovice.jp/articles/128
https://railsguides.jp/routing.html

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?