When to create a new controller in rails

UPDATE: I highly recommend reading How DHH Organizes His Rails Controllers
which pretty much explains it much better than my original answer.

I think the question would be more suitable if you’d put it another way:

Why do we need model (AR in this case) for every controller?

And the answer of course is, you don’t. When you are thinking about controllers it’s best not to think about data, but take a slight step back, and think about resources. If you search for REST in internet, you will find a lot of articles and most of them will include various explanations of terms resource and representation. To make this story short, let’s just oversimplify and say that resource is everything that’s worth mentioning. Articles is a (collection) resource. Store is a (singular, member) resource.

Take signing in users for example. You probably already have UsersController which (by default) will allow you adding new users (create resource), deleting them (remove resource), displaying single user and also all users. If you just think in terms of data and controllers, you probably would start creating additional actions like login_user in UserController, which is a smell. If you think about resources, and that is “everything that’s worth mentioning about or creating URI for it”, you might think that you need another resource, and that is: sessions. Think about this way: when user signs in, they actually create a session resource. And with sign out, you delete, remove the resource. It is much better explained in the Rails tutorial book which I recommend: http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions

To recap, this may help you in figuring out when you need new controller:

  • When you think about putting non RESTful actions in controller like log_in, calculate_date, ect.
  • When there is something that you can name and that is “interesting” enough to be a separate resource.
  • Also, when you are developing in “outside in” style, such answers come more naturally: http://rubylearning.com/blog/2010/10/05/outside-in-development/

Overall, learning about REST and its philosophy will help a lot.

Leave a Comment