user1287523
user1287523

Reputation: 957

Is it bad practice to have very large controllers in Rails (and other MVC frameworks)?

I'm a student and have been learning rails on my own time. So far, I'm able to develop simple applications that only perform standard database operations. Currently, I'm attempting to increase my knowledge and seeing how I can make applications that actually "do things" rather than just being simple database skins.

I decided to take a look at some open-source rails applications to see how professionals do it. One of the ones recommended on this site was Tracks. I briefly went over the source code and was shocked at how large some of the controllers are. For instance, the todos controller is over 1400 lines. Is this normal? Should this code be refactored out and placed somewhere else? If so, where is it supposed to be placed? Or, is it normal to have very large controllers like this?

Upvotes: 3

Views: 662

Answers (2)

Mastfish
Mastfish

Reputation: 78

Generally speaking it's bad practice to have such large controllers.

The logic should generally be moved into models whenever possible. A good article on this: http://www.sitepoint.com/10-ruby-on-rails-best-practices/.

There's an excellent gem called "rails best practices" that I find extremely helpful to improve my code style, https://github.com/railsbp/rails_best_practices .(Relevant page, http://rails-bestpractices.com/posts/7-move-model-logic-into-the-model)

Upvotes: 1

Pablo Fernandez heelhook
Pablo Fernandez heelhook

Reputation: 12583

You will encounter different opinions and different takes on this, "fat model, skinny controller" is a popular one, and one that many people in the Ruby on rails community subscribe to. To a degree, a lot of code should be in a model, when it makes sense for the object to provide certain attributes and characteristics.

Starting with a test (as in, doing TDD) helps a lot in realizing what belongs in a controller and what belongs in a model, as it poses the right question when creating the test who/what should behave in which way.

A good post by @dhh about this in http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns

Upvotes: 1

Related Questions