concernを使ったおなじみルートの追加

確認画面とか、いろんなページで同じルートを設定する場合に便利。

例えばこんな感じで確認画面のルートを設定していた場合、

resources :users do
  patch :confirm, :on => :member
  put   :confirm, :on => :member
  post  :confirm, :on => :collection
end

resources :information do
  patch :confirm, :on => :member
  put   :confirm, :on => :member
  post  :confirm, :on => :collection
end

routes.rb

concernを使うとこんなにスッキリ!

concern :confirmable do
  patch :confirm, :on => :member
  put   :confirm, :on => :member
  post  :confirm, :on => :collection
end

resources :users, :concerns => :confirmable
resources :information, :concerns => :confirmable

routes.rb

こうすると、 rake routes ではこんな感じ。

$ rake routes | grep "users\|information"
                  confirm_user PATCH    /users/:id/confirm(.:format)       users#confirm
                                 PUT    /users/:id/confirm(.:format)       users#confirm
                   confirm_users POST   /users/confirm(.:format)           users#confirm
                           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
      confirm_system_information PATCH  /information/:id/confirm(.:format) information#confirm
                                 PUT    /information/:id/confirm(.:format) information#confirm
confirm_system_information_index POST   /information/confirm(.:format)     information#confirm
        system_information_index GET    /information(.:format)             information#index
                                 POST   /information(.:format)             information#create
          new_system_information GET    /information/new(.:format)         information#new
         edit_system_information GET    /information/:id/edit(.:format)    information#edit
              system_information GET    /information/:id(.:format)         information#show
                                 PATCH  /information/:id(.:format)         information#update
                                 PUT    /information/:id(.:format)         information#update
                                 DELETE /information/:id(.:format)         information#destroy


Qiitaに投稿した記事です。