Rails routing 早見表
先月から新しくバックエンドでRailsを使ったプロダクトにアサインさせていただきました。
これまで、nodeで開発をしてきた僕からすると、Railsの独自実装が使いにくすぎたので、メモとして残しておきます。
(AIにまとめさせた内容をそのまま貼り付けています)
Railsで学ぶルーティングとresourcesの基本まとめ
Rails を勉強し始めると必ず出てくるのが resources。
しかし Hono や Express などの「ルートを1本ずつ書く」スタイルに慣れていると、
なぜ Rails は resources でまとめて書けるのか、show って何?と戸惑うことも多いです。
この記事では、Rails のルーティング DSL と resources を理解するために最低限必要な知識をまとめます。
Ruby と Rails の関係
- Ruby 本体には
resourcesというメソッドは存在しません。 -
resourcesは Rails が ルーティング DSL(Domain Specific Language)として提供している独自メソッドです。 - Ruby の文法である「ブロック (
do ... end)」と「シンボル (:reservations)」を利用しています。
resources :reservations do
member do
post :confirm
end
end
-
resources… Rails が提供するメソッド -
:reservations… Ruby のシンボル(名前を軽量に扱うデータ型)
RESTful ルーティングと7つのアクション
resources :posts と書くと、Rails は自動で 7つの標準アクションに対応するルートを生成します。
| アクション | HTTP | パス | 役割 |
|---|---|---|---|
| index | GET | /posts | 一覧取得 |
| show | GET | /posts/:id | 単体取得 |
| new | GET | /posts/new | 新規フォーム表示 |
| create | POST | /posts | 新規作成 |
| edit | GET | /posts/:id/edit | 編集フォーム表示 |
| update | PATCH | /posts/:id | 更新 |
| destroy | DELETE | /posts/:id | 削除 |
APIモードでは new と edit は不要なので、よく only オプションで絞ります。
resources :posts, only: [:index, :show, :create, :update, :destroy]
パラメータ名とid
Rails の resources はデフォルトで :id を使います。
resources :reservations
# => /reservations/:id
# => params[:id]
親子リソースでは自動的に :親名_id が使われます。
resources :practitioners do
resources :reservations
end
# /practitioners/:practitioner_id/reservations/:id
もしパラメータ名を変えたい場合は param: オプションを使えます。
resources :reservations, param: :reservation_id
# => /reservations/:reservation_id
# => params[:reservation_id]
よく使うオプション・構文まとめ
1. only / except
必要なルートだけ定義する。
resources :reservations, only: [:index, :show, :create]
resources :reservations, except: [:new, :edit]
2. member / collection
CRUD以外のアクションを追加。
resources :reservations do
member do
post :confirm # /reservations/:id/confirm
end
collection do
get :search # /reservations/search
end
end
3. ネストと shallow
親子リソースを表現。
resources :practitioners do
resources :reservations, shallow: true
end
# /practitioners/:practitioner_id/reservations
# /reservations/:id
4. namespace / scope
API のバージョニングや管理画面用。
namespace :api do
namespace :v1 do
resources :reservations
end
end
# /api/v1/reservations
スコープでパスだけ変更することもできる:
scope path: "/admin" do
resources :reservations
end
# /admin/reservations
5. defaults
デフォルトのレスポンス形式を指定。
resources :reservations, defaults: { format: :json }
ルートの確認
どんなルートが生えているかは bin/rails routes で確認できます。
bin/rails routes -g reservation
まとめ
-
resourcesは Ruby 標準ではなく Rails 独自のルーティング DSL -
:reservationsは Ruby のシンボルで、リソース名を表す - デフォルトで
:idパラメータを使う(親は:parent_id) - よく使うオプションは
only/except,param:,member/collection,namespace,defaults - API 開発なら基本は index/show/create/update/destroy の5アクション だけ覚えれば十分
🚀 Hono や Express のように「1本ずつルートを書く」フレームワークに慣れていても、Rails の resources を理解すれば 短いコードでRESTful APIを一気に構築できる のでかなり効率的です。
Discussion