This post originated from an RSS feed registered with Ruby Buzz
by Guy Naor.
Original Post: How Far Should the Models Go?
Feed Title: Famundo - The Dev Blog
Feed URL: http://devblog.famundo.com/xml/rss/feed.xml
Feed Description: A blog describing the development and related technologies involved in creating famundo.com - a family management sytem written using Ruby On Rails and postgres
Recently I had a discussion with some other developers regarding the line separating models and controllers in MVC. The issue is, how much logic should go into the model, and how much in to the controller.
I see many places where the model is left with the CRUD actions only, and maybe a few small things. The rest falls on the hands of the controller.
My preference is to have the business logic pushed as much as possible into the model. Of course there is cross model stuff that must be handled in the controllers (authentication and authorization for example), but the more we push clean login into the model, the less we have to worry about repeating ourselves in the controllers, and the less bugs will be introduced that are not covered by unit tests.
The way I implement it, is that my models have some high level methods that handle complex operations that relate to the model. An example will make it clear. Say we have a content management system, with a content model. The content model has publish_at attribute, and we need to get all the items we need to show, based on this attribute and a count of how many items to show, ordered by the published_at attribute. I'll use rails here, but it applies to any MVC system.
Or, the way I prefer it - at the controller we call:
published_items = Content.get_published_items(15)
And we put the find in the model itself. This way we encapsulate the find and expose the logic. If we now need the published item elsewhere (on a side bar, on an index page) we just call the same model function from other controllers.