Rails routesを書く時の注意点(超基本)
routes.rbを書く時
基本形 (Scaffold準拠にルーティングを追加するとき)
単数なのか複数なのか、注意すること。
- resource
- resources
複数形リソース
一番基本形 (resources) キーワード、リソース名ともに複数形
使用例:
resources :products
生成されるパス
Scaffold基本形と完全一致(7つ)
Prefix Verb URI Pattern Controller#Action products GET /products(.:format) products#index POST /products(.:format) products#create new_product GET /products/new(.:format) products#new edit_product GET /products/:id/edit(.:format) products#edit product GET /products/:id(.:format) products#show PATCH /products/:id(.:format) products#update PUT /products/:id(.:format) products#update DELETE /products/:id(.:format) products#destroy
単数形リソース
どういう時に単数形リソースを使うかの参照記事 Rails のルーティング | Rails ガイド
場合によっては、ユーザーがページを表示する時にidを参照することのないリソースが使用されることがあります。たとえば、/profileでは常に「現在ログインしているユーザー自身」のプロファイルを表示し、他のユーザーidを参照する必要がないとします。このような場合には、単数形リソース (singular resource) を使用してshowアクションに (/profile/:idではなく) /profileを割り当てることができます。
使用例:
resource :profile
生成されるパス (index は生成されない) :idもない
Prefix Verb URI Pattern Controller#Action product POST /product(.:format) products#create new_product GET /product/new(.:format) products#new edit_product GET /product/edit(.:format) products#edit GET /product(.:format) products#show PATCH /product(.:format) products#update PUT /product(.:format) products#update DELETE /product(.:format) products#destroy page GET /pages/*id high_voltage/pages#show
単語の単数形複数形に注意
resource :products
とかやると、意味がわかりにくいので注意。
id指定なしでアクセスできる単数形リソースを作ろうとしている時は、リソース名も単数形にした方がいい。
Scafolldと同じrouting書こうと思ってたのに、何故かindexアクションが生成されてない!?と思ったら、ウッカリ resouce (s忘れ)してないかチェックすること。