Ruby on Rails/Getting Started/Model-View-Controller

Previous: Getting Started/Don´t repeat yourself Index Next: Getting Started/Convention Over Configuration

Model-View-Controller

edit
 
MVC-Architecture inside Rails

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

Model

edit

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.

View

edit

The view is the presentation layer for your application. The view layer is responsible for rendering your models into one or more formats, such as XHTML, XML, or even Javascript. Rails supports arbitrary text rendering and thus all text formats, but also includes explicit support for Javascript and XML. Inside the view you will find (most of the time) HTML with embedded Ruby code. In Rails, views are implemented using ERb by default.

Controller

edit

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.

Helpers

edit

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.

Best Practices

edit

Current best practices include:

  • fat model and skinny controller
  • business logic should always be in the model
  • the view should have minimal code
  • Use helpers!
  • use models
  • DRY (Don't Repeat Yourself)