Using resources with custom controller names

2019-04-04 05:57发布

问题:

I'm using nested resources, however i come across controller names that should be more descriptive.

For instance i have a controller ProductsController and ImagesController

resources :products do
  resources :images
end

This works fine, but later i might need to use the ImageController for other than products images, therefore it should be named ProductsImagesController.

But how can i specify the controller name on resources() without falling back to something ugly like:

match 'products/images' => 'products_images#index'
match 'products/images/new' => 'products_images#new'

回答1:

resources :products do
  resources :images, :controller => "products_images"
end


回答2:

Coming from a Zend Framework background, I think you are looking for a modular structure. Rails seems to offer this, called 'namespacing':

namespace :admin do
  resources :posts, :comments
end

That creates routes to Admin::PostsController and Admin::CommentsController. In your case, you would have Products::ImagesController.

http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing

I found out from this other accepted answer: zend modules like in rails