Ruby on Rails/Getting Started/Model-View-Controller
As already mentioned, Rails relies on the MVC pattern. Model-View-Controller has some benefits over traditional concepts:
- it keeps your business logic separated from your (HTML-based) views
- keeps your code clean and neat in one place
The model represents the information and the data from the database. It is as independent from the database as possible (Rails comes with its own O/R-Mapper, allowing you to change the database that feeds the application but not the application itself). The model also does the validation of the data before it gets into the database. Most of the time you will find a table in the database and an according model in your application.
The controller connects the model with the view. In Rails, controllers are implemented as ActionController classes. The controller knows how to process the data that comes from the model and how to pass it onto the view. The controller should not include any database related actions (such as modifying data before it gets saved inside the database). This should be handled in the proper model.
When you have code that you use frequently in your views or that is too big/messy to put inside of a view, you can define a method for it inside of a helper. All methods defined in the helpers are automatically usable in the views.
Current best practices include:
- fat model and skinny controller
- business logic should always be in the
- the view should have minimal code
- Use helpers!
- use models
- DRY (Don't Repeat Yourself)