Model View Controller | <= Business logic goes in here |
It sure does.
As a general rule I avoid blogging about the obvious, but sometimes what's obvious varies from person to person. I've run into the misconception that Rails does not support this obvious statement, that business logic goes into the Model. In Rails, according to this misconception, the Model is simply a Data Access Layer, and business logic winds up in the helpers or elsewhere. The purpose of this post is mainly to give me something to link to or copy and paste as the mood strikes me when I next run into this misconception.
In Ruby on Rails, as in any good MVC framework, business logic goes in the Model. All of it. Every shred of it.
I'm currently working on a project to develop a point-of-sale and online purchasing system with a great deal of very complex (some might argue overly complex) business logic. Simply displaying the available quantity of a specific item involves considering at which warehouse the order is being fulfilled, the quantities in various bins, and quantities from the bins which have already been allocated to an order but not yet pulled.
None of that business logic is in the Controller. None of it is in the View. And none of it is in a helper. It's all in the Model. The only thing the View needs to do is this:
item.quantity_available
A helper is simply a module containing methods that assist a view. Helper methods are output-centric. They exist to generate HTML (or XML, or JavaScript) -- a helper extends the behavior of a template.Put another way, you can off-load code to the helper to avoid putting too much into your View templates.
-- Agile Web Development With Rails, Dave Thomas, David Heinemeier Hansson
For further reading on this topic, here's a few handy links:
- Skinny Controller, Fat Model by Jamis Buck
- RailsConf Recap: Skinny Controllers by Jamis Buck
- Skinny Controller, Fat Model by Colin A. Bartlett
- Find methods in controllers by Graeme Nelson
- Rspec notes from the trenches-2 by Courtenay over on Caboo.se