Controller Anti-patterns in Rails
Now that you know what a good controller looks like, let's see what a bad controller looks like to help you stay away from creating a bad one.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Now that you know what a good controller looks like, let's see what a bad controller looks like to help you stay away from creating a bad one.

A controller is undoubtedly an important part of your application. Since it gives a direct connection to view files, it feels logical to put all your code in here. However, the problem with this approach is that it can get messy, especially when you're dealing with tons of code.

To give you an idea of what a bad controller looks like, I brought a file from a different project and called it messy_controller.rb. Here are some snapshots of this file.

large

large

large

The first thing you'll see is the length of this file. With 323 lines of code, this file is way too big and can get out of hands quickly for even experienced developers. It makes it difficult to understand what methods are getting called inside view files, and to even get a hang of the application's flow.

This is why Rails advocates skinny controllers and fat models. In this case, the ideal way would be to put a sizable chunk of the code into a model file.

Also, this controller should have more classes because typically in Ruby, you should use a class only to do one particular task. If you take the case of our ProjectsController class in our projects_controller.rb file, it has only one goal and that is to setup a flow of data between the view and model for the "projects" feature of this site. This is why it's clean and easy to understand.

In short, when you follow these rules, you will have a cleaner interface and it will help developers when they come into the project, not to mention the good programming practice that it will follow. Keep these points in mind while building out your own controllers in the future.