【Rails】リソースフルルートにおけるonly,except,controller,pathオプションを分かりやすく整理する

プログラミング

【Rails】リソースフルルートにおけるonly,except,controller,pathオプションを分かりやすく整理する

どうも、てーやまです。

Railsのルーティングでは「resources」を使用する事で、標準的なHTTPメソッドと「コントローラ#アクション」へのルートを1行で実装することができます。

今回はそのリソースフルルートに対するonly,except,controller,pathオプションを整理してみようと思います。

リソースフルルート

リソースフルルートの復習です。
たった1行、以下のように記載するだけでルートが作成されます。便利。

resources :studies
ルーティング
ヘルパー
HTTPメソッドパスコントローラ#
アクション
機能
studies_pathGET/studiesstudies#index一覧照会画面
new_study_pathGET/studies/newstudies#new新規登録画面
POST/studiesstudies#create登録処理
edit_study_pathGET/studies/:id/editstudies#edit編集画面
PATCH/studies/:idstudies#update更新処理
PUT/studies/:idstudies#update更新処理
study_pathGET/studies/:idstudies#show詳細画面
DELETE/studies/:idstudies#destroy削除処理
リソースフルルートによって作成される標準的なルーティング

ちなみに、上記のように設定済のルートはブラウザから「http://localhost:3000/rails/info/routes」にアクセスすることによって確認することができます。

もしくはターミナルからrailsコマンド「rails routes」を入力しても確認できます。

リソースフルルートのオプション

リソースフルルートは非常に便利ですが、汎用性に欠けます。

例えば以下のようにカスタマイズしたい場合はどうしたら良いのでしょう。

  • 特定のアクションにのみルートを定義したい
  • ルートに対応するコントローラを変更したい
  • ルートのURL(パス)を変更したい

こういった要望に応える機能が以下に示す「オプション」です。
一つずつ見ていきましょう。

only

指定したアクションにのみ、ルートを定義します。
複数指定する場合には、配列を使います。

resources :studies, only: [:index, :new, :create]

上記のように記述することで「studies#index」,「studies#new」,「studies#create」の3つのルート以外、定義されません。

except

指定したアクションのみ、ルートを定義しません。
要は「only」オプションの逆の機能です。

resources :studies, except: [:index, :new, :create]

上記のように記述することで「studies#index」,「studies#new」,「studies#create」の3つのルートは、定義されません。

それ以外の「studies#edit」,「studies#update」,「studies#show」,「studies#destroy」のルートが定義されます。

controller

ルートに対応するコントローラを変更します。

resources :studies, controller: :student
ルーティング
ヘルパー
HTTPメソッドパスコントローラ#
アクション
機能
studies_pathGET/studiesstudent#index一覧照会画面
new_study_pathGET/studies/newstudent#new新規登録画面
POST/studiesstudent#create登録処理
edit_study_pathGET/studies/:id/editstudent#edit編集画面
PATCH/studies/:idstudent#update更新処理
PUT/studies/:idstudent#update更新処理
study_pathGET/studies/:idstudent#show詳細画面
DELETE/studies/:idstudent#destroy削除処理
対応するコントローラが「student」に変わりました

path

ルートのURL(パス)を変更します。
要は「controller」オプションの逆の機能です。

resources :studies, path: :student
ルーティング
ヘルパー
HTTPメソッドパスコントローラ#
アクション
機能
studies_pathGET/studentstudies#index一覧照会画面
new_study_pathGET/student/newstudies#new新規登録画面
POST/studentstudies#create登録処理
edit_study_pathGET/student/:id/editstudies#edit編集画面
PATCH/student/:idstudies#update更新処理
PUT/student/:idstudies#update更新処理
study_pathGET/student/:idstudies#show詳細画面
DELETE/student/:idstudies#destroy削除処理
ルートのURL(パス)が「student」に変わりました

次の更新では、「path_names」,「as」,「collection」,「member」オプションについて

また、リソースフルルート以外のルート(match…:via),
グループ化(scope,namespace)についても備忘録を作っていくつもりです。

それでは〜。