Rails 3 Routing: Adding an Action to All Resources in the Namespace

I am developing my admin panel for cms, and I want, for example, to download, images and articles. Each of these elements can be classified, so I have a “category” action on each controller (“Downloads, Images, and Articles”).

In the routes file, I have the following:

namespace :admin do resources :downloads resources :images resources :articles end 

My problem is that the above code creates routes for the index, shows, edits, updates and destroys. Is there a way to add category action to all resources once without announcing it 3 times?

+4
source share
2 answers
 namespace :admin do [:downloads, :images, :articles].each do |resource| resources resource do get :categories, :on => :collection end end end 
+6
source

If you need a smaller control, you can also provide your own custom resource method:

 Rails.application.routes.draw do def resources_with_count(*params, &block) resources *params do collection do get :count end end resources *params, &block end # This will now generate regular resources, but also add the /users/count route as well resources_with_count :users do resources :comments end resources_with_count :posts end 
0
source

All Articles