Rails Model, View, Controller, and Helper: what goes where?

theschmitzer picture theschmitzer · Sep 13, 2008 · Viewed 43.1k times · Source

In Ruby on Rails Development (or MVC in general), what quick rule should I follow as to where to put logic.

Please answer in the affirmative - With Do put this here, rather than Don't put that there.

Answer

pauliephonic picture pauliephonic · Sep 13, 2008

MVC

Controller: Put code here that has to do with working out what a user wants, and deciding what to give them, working out whether they are logged in, whether they should see certain data, etc. In the end, the controller looks at requests and works out what data (Models) to show and what Views to render. If you are in doubt about whether code should go in the controller, then it probably shouldn't. Keep your controllers skinny.

View: The view should only contain the minimum code to display your data (Model), it shouldn't do lots of processing or calculating, it should be displaying data calculated (or summarized) by the Model, or generated from the Controller. If your View really needs to do processing that can't be done by the Model or Controller, put the code in a Helper. Lots of Ruby code in a View makes the pages markup hard to read.

Model: Your model should be where all your code that relates to your data (the entities that make up your site e.g. Users, Post, Accounts, Friends etc.) lives. If code needs to save, update or summarise data related to your entities, put it here. It will be re-usable across your Views and Controllers.