MVC Pattern in Ruby on Rails

In this article, we will talk about how Ruby on Rails implements the MVC pattern. MVC (Model, View, Controller) was first described and implemented into the Smalltalk-79 user interface paradigm by Trygve Reenskaug. Its purpose was to allow the user to access and edit complex data in an accessible manner.

what is the mvc pattern?

The MVC pattern consists of three parts: model, view, and controller.

The model is a representation of data in a computing system.

A view is a visual representation of a model. A model can have multiple views, each representing a point of view. Therefore, it can show some of its attributes, ignoring attributes that are not relevant in that perspective.

The controller makes the connection between the user and the system. It shows the relevant view to a user request.

The rAILS iMPLEMENTATION OF THE mvc PATTERN

The Rails framework implements this MVC pattern using a series of conventions. This implementation is done through three modules: ActiveRecord, ActionController, and ActionView.

In Rails, a model is a Ruby class that communicates with the database through an interface called Active Record. Active Record can do a series of things with models. It can represent models, represent associations between models, validate them, and perform database operations. By convention, the model names are singular. All the models live inside the app/models/ folder.

The views and the controllers of a Rails application share the same name. Controller and views names are plurals. The controllers live in the app/controllers/ folder, and views live in the app/views/ folder.

Users navigate a website by making requests to different pages. The Rails router forwards a web request to a controller action. Then the controller displays the view with the same name as the action. 

In views, we can access only the attributes relevant to that view. Suppose you have a blog application, and you only want to show a list of post titles on your home page. You do that by first creating an instance variable in the controller:

@posts = Post.all

And then in views: 

<ul>
  <% @posts.each do |post| %>
    <li><%= post.title %></li>
  <% end %>
</ul>

In Rails, the data sent in by the users via forms or queries is available in the params hash of the controller. The parameters of this hash are then sent to the database to retrieve, create, update or delete resources.

Bibliography

1.  Trygve Reenskaug, “MVC/XEROX PARC 1978-79”, https://folk.universitetetioslo.no/trygver/themes/mvc/mvc-index.html.

2. Rails Guides, https://guides.rubyonrails.org/.

Post last updated on May 13, 2023