Reputation: 26008
If I have to have the controllers those would look like this
namespace :somearea do
resources :users do
resources :posts do
resources :comments
end
end
end
then how do I name them? Is it ok to name them like following:
class SomeArea::BaseController < ApplicationController
end
class SomeArea::UsersController < SomeArea::BaseController
end
class SomeArea::Users::PostsController < SomeArea::BaseController
end
class SomeArea::Users::Posts::CommentsController < SomeArea::BaseController
end
This is not the exact hierarchy in my project, but nonetheless I want to be able to understand how I should name the controller in my case.
Upvotes: 0
Views: 380
Reputation: 26193
The examples you listed are indeed syntactically acceptable, but it's not considered good practice to create such deeply nested routes. From the canonical Rails guide on routing:
Deeply-nested resources quickly become cumbersome... Resources should never be nested more than 1 level deep.
The guide goes on to reference this article by Jamis Buck regarding nesting Rails routes. If you're truly going to nest your routes as you've depicted, it's worth a read to understand the implications of doing so.
Upvotes: 0
Reputation: 491
You can do the following:
class SomeAreaController < ApplicationController
end
class UsersController < ApplicationControllerr
end
class PostsController < ApplicationController
end
class CommentsController < ApplicationController
end
since the way you propose only implies the directory structure and it does not infer the nested resources. E.g SomeArea::Users::PostsController
means that your posts_controller.rb
is located in app/controllers/some_area/users/
folder.
The fact that Users/Posts/Comments inherit from SomeArea::BaseController
it is up to you but again it is not explicitly attributable to the the fact that your are considering nested resources.
Upvotes: 0
Reputation: 3727
The nested routes in this case only really apply to how the routes are set up. You do not need to nest the controllers in modules the way you are doing it here. In fact, I think that if you do that, you may need to change the routes to be able to find the nested controllers. I would say you want the following:
class SomeArea::BaseController < ApplicationController
end
class SomeArea::UsersController < SomeArea::BaseController
end
class SomeArea::PostsController < SomeArea::BaseController
end
class SomeArea::CommentsController < SomeArea::BaseController
end
EDIT - as said in zeantsoi's answer, having routes nested this deeply is considered bad practice, or at least something to be avoided if possible. But if, for whatever reason you are required to do this, I would still say that you shouldn't bother nesting all the classes inside modules in code. It would make things even more cumbersome.
Upvotes: 2