← Back to Upcase

What's your thoughts in organizing controllers in folders?


(John Enrico Monsanto) #1

I’ve seen this DHH article (Organizing Controllers a la DHH) where he organizes non-CRUD methods in a separate controller. This somehow I can understand the rationale.

However, I’m working on this project which is at its infancy stage. And I’m seeing this for the first time:

controllers/
  topics/
    topics_controller.rb
  posts/
    posts_controller.rb

So you can imagine namespaces such as Posts::PostsController and etc. Routes riddled with nested scope modules: <resource>

I asked the reason why we’re doing it like this, and the argument is to keep things organized.

I’m always a proponent of simple engineering and unnecessary abstractions. To have messy routes and protracted namespaces is too much just to keep things organized or maybe I’m just lacking experience in Rails and this is a thing already and I’m behind the times.

So with that being said, what are your thoughts? And how do you do (organize) yours?


(Carlos Ramirez III) #2

I have used the strategy in the original article with good results, but I’ve never come across a project which organized all controllers into namespaces like what you show above. To me, it seems like premature organization at best, unnecessary at worst. I’d be much more in favor of adding a namespace when there’s a reason to. Doing it this way cuts against the grain of the Rails conventions which makes life harder for what appears like not a lot of benefit.


(Nathan) #3

I use namespaces for nested resources or for separate areas of the app (like admin vs. customer)

I don’t put a top level resource in a name of its own. So, I wouldn’t have Posts::PostsController, just PostsController.

However, if I wanted the posts for a particular topic, it would be Topics::PostsController like this:

resources :topics do
  resources :posts, controller: 'topics/posts'
end

Then, by convention, any controller inside the Topics namespace is going to have a :topic_id param.

This approach also allows me to have multiple controllers named the same thing within different namespaces, where the namespace fully describes the context.

So, PostsController is for all posts in the system, Topics::PostsController is for all posts for the given topic, and Authors::PostsController is for all posts for the given author. Note: sometimes this doesn’t play well with Rails’ autoloading, so I use require_dependency pretty liberally.