Models, Views and Controllers

Get familiar with the Rails MVC model in this lesson.

Back in 1979, Trygve Reenskaug came up with a new architecture for developing interactive applications. In his design, applications were broken into three types of components: models, views, and controllers.

Models

The model is responsible for maintaining the state of an application. Sometimes this state is transient, lasting for just a couple of interactions with the user. Sometimes the state is permanent and is stored outside the application, often in a database.

A model is more than data. It enforces all the business rules that apply to that data. For example, if a discount shouldn’t be applied to orders of less than $20, the model enforces that constraint. By putting the implementation of these business rules in the model, we make sure that nothing else in the application can make our data invalid. The model acts as both a gatekeeper and a data store.

Views

The view is responsible for generating a user interface, which is normally based on data in the model. For example, say an online store has a list of products to be displayed on a catalog screen. This list is accessible via the model, but it’s the view that formats the list for the end-user. Although the view might present the user with various ways of inputting data, the view itself never handles incoming data. The view’s work is done once the data is displayed. There may well be many views that access the same model data, often for different purposes. The online store has a view that displays product information on a catalog page and another set of views used by administrators to add and edit products.

Controllers

Controllers orchestrate the application. Controllers receive events from the outside world ( normally, user input). They also interact with the model, and display an appropriate view to the user.

This combination of the model, view, and controller together form an architecture known as MVC. To learn how the three concepts fit together, see the following figure.

MVC architecture

Get hands-on with 1200+ tech skills courses.