railsで自動作成以外に自分でルート追加する方法
railsで自動作成以外に自分でルート追加する方法
毎回忘れるのでメモ
member
resources :users do member do get :option end end
以上のようにmemberを使うと以下のようなルートを作ることが出来る
GET /users/:id/option
collection
resources :users do collection do get :option end end
:idなどのパラメータを使いたい場合はcollectionを使います。
GET /users/option
(2019/2/5追加) namespace
namespace :admin do resources :staffs end
namespaceを使うとルートとコントローラーの頭にadminをつける事が出来ます。
admin_staffs GET /admin/staffs(.:format) admin/staffs#index POST /admin/staffs(.:format) admin/staffs#create new_admin_staff GET /admin/staffs/new(.:format) admin/staffs#new edit_admin_staff GET /admin/staffs/:id/edit(.:format) admin/staffs#edit admin_staff GET /admin/staffs/:id(.:format) admin/staffs#show PATCH /admin/staffs/:id(.:format) admin/staffs#update PUT /admin/staffs/:id(.:format) admin/staffs#update DELETE /admin/staffs/:id(.:format) admin/staffs#destroy
(2019/2/5追加) module
resources :staffs, module: 'admin'
namespaceの代わりにmoduleを使うとコントローラの頭だけにadminをつける事が出来ます。
staffs GET /staffs(.:format) admin/staffs#index POST /staffs(.:format) admin/staffs#create new_staff GET /staffs/new(.:format) admin/staffs#new edit_staff GET /staffs/:id/edit(.:format) admin/staffs#edit GET /staffs/:id(.:format) admin/staffs#show PATCH /staffs/:id(.:format) admin/staffs#update PUT /staffs/:id(.:format) admin/staffs#update DELETE /staffs/:id(.:format) admin/staffs#destroy
まとめ
resourceでルート自動作成した後に、ルート追加したいケースは多いのでこの技は良く使います。