🚀 Ruby on Rails: MVC and you!
Tags: rails, ruby, frontend, beginners
Published: 2024-01-18 12:07:03

For any aspiring Ruby on Rails developer, understanding the Model-View-Controller (MVC) architecture is akin to mastering the alphabet of web development.

 It's the foundational framework upon which your applications are built, ensuring a structured, modular, and maintainable codebase. 

This article explores the Rails MVC architecture, equipping you with the knowledge and practical examples to navigate your web development journey with confidence.

## Table of Contents
&nbsp;1. [The Pillars of the MVC architecture: Model, View, Controller](#the-pillars-of-the-mvc-architecture-model-view-controller)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1.1. [The Model](#the-model)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; a. [Data Representation](#data-representation)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; b. [Database Interactions](#database-interactions)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; c. [Business Logic](#business-logic)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1.2. [The View](#the-view)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; d. [Templates](#templates)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e. [Helpers](#helpers)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; f. [Layout and Assets](#layout-and-assets)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1.3. [The Controller](#the-controller)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; g. [Actions](#actions)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; h. [Routing](#routing)
&nbsp;2. [The Rails MVC architecture working together](#the-rails-mvc-architecture-working-together)
&nbsp;3. [Benefits of the MVC Architecture](#benefits-of-the-mvc-architecture)
&nbsp;4. [References](#references)

##The Pillars of the MVC architecture: Model, View, Controller


![Rails MVC architecture](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4irgli819runh0v8q1hn.png)

Imagine your application as a movie production.
The **Model** represents the crew of the movie—working in the background of the entire production to make things happen. The **View** is the stage and scenery—all the things you can see and interact with. The **Controller** acts as the director of the movie, dictating what each part or component on set should do. Each component plays a distinct role, collaborating seamlessly to deliver a captivating experience for your users.

###The Model

A model is a Ruby class that is used to represent data. Additionally, models can interact with the application's database through a feature of Rails called Active Record.
To define a model, we will use the model generator:
The Model layer is the central component of any Rails application; it handles the data that powers your webpages and contains the business logic that specifies how data is created, read, updated, and deleted (CRUD operations). You can think of the Model layer as the backstage crew that makes sure the actors are properly attired and prepared for their parts.

####Data Representation
Models represent real-world entities like users, products, or orders. They define attributes, relationships, and validations for each entity. For instance, a `User` model might have attributes like `name`, `email`, and `password`, with validations ensuring email uniqueness and password strength.

####Database Interactions 
Models act as intermediaries between your application and the database. They provide methods for data retrieval, manipulation, and persistence. Imagine a `Product` model retrieving information from a `products` table or updating its price in the database.

####Business Logic 
Models encapsulate the core logic of your application. They define rules and calculations specific to your domain. For instance, a `Cart` model might calculate the total cost of items based on quantity and price.

To define a model, we will use the model generator:

```shell
 bin/rails generate model Product name:string price:number
```

In the example above, we are trying to generate a model for products on an ecommerce page. The database is being told that each product will have the attributes name and string.  

###The View

The View layer takes the data provided by the Model and transforms it into the visual representation users interact with. It generates HTML content, CSS styles, and JavaScript code that paint the picture of your application on the user's screen. Think of it as transforming the raw data into a visual format.

####Templates
Views are typically written in ERB (Embedded Ruby) templates, allowing dynamic content generation based on data received from the Model. Imagine a `products/index.html.erb` template iterating through a list of products and displaying their names, prices, and images.

####Helpers
View helpers provide reusable snippets of code for common tasks like formatting dates, generating forms, or displaying error messages. They help keep your views clean and maintainable.

####Layout and Assets
Views can inherit layout templates that define the overall structure of the page, including headers, footers, and sidebars. Additionally, separate CSS and JavaScript files handle styling and interactivity, respectively.

**Code Sample:**

```erb
<h1>Products</h1>
<% @products.each do |product| %>
  <div class="product">
    <h2><%= product.name %></h2>
    <p><%= product.description %></p>
    <p>Price: $<%= product.price %></p>
    <%= link_to "Add to Cart", add_to_cart_path(product), class: "btn btn-primary" %>
  </div>
<% end %>
```

###The Controller

The Controller acts as the bridge between the Model and the View. It receives user requests, interacts with the Model to retrieve or manipulate data, and prepares the data for presentation in the View. Think of it as the conductor, interpreting user actions and directing the cast and crew to deliver the appropriate response.

####Actions
Controllers define `methods` called actions that handle specific user requests. For instance, a `ProductsController` might have an `index` action to display all products or a `show` action to display a specific product.

####Routing
In Ruby on Rails, routing refers to the process of determining how an incoming HTTP request should be handled by the application. The routing system in Rails maps URLs to controller actions, helping to organize and structure your web application. Routes are defined in the `config/routes.rb` file.

Here's an example of a ProductsController in Rails:

```ruby
class ProductsController < ApplicationController
  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      redirect_to products_path, notice: 'Product created successfully'
    else
      render :new, status: :unprocessable_entity
    end
  end

  private

  def product_params
    params.require(:product).permit(:name, :price)
  end
end
```

This controller defines actions for listing products `index`, showing a specific product `show`, and creating a new product `create`. It interacts with the `Product` model to retrieve and manipulate data, and instructs the appropriate Views on how to render the response.

##The Rails MVC architecture working together

The MVC architecture fosters a symbiotic relationship between these three components. A user requesting a list of products triggers the following flow:

- The controller receives the request and identifies the 
  appropriate action (e.g., `index`).
- The controller interacts with the Product model to retrieve a 
  list of all products.
- The controller passes the retrieved products `@products` to the 
  `products/index.html.erb` view.
- The view iterates through the @products collection and generates 
  HTML content displaying the product names and prices.
- The generated HTML content is sent back to the user's browser, 
  rendering the product list on the screen.

##Benefits of the MVC Architecture

- Clarity and Maintainability: Separating concerns into distinct 
  layers enhances code readability and maintainability. Developers 
  can focus on specific aspects without getting bogged down in 
  unrelated code.
- Reusability: Models can be reused.

## References
[Cover image]([https://www.google.com/url?sa=i&url=https%3A%2F%2Fdev.to%2Frutikkpatel%2Fthe-importance-of-mvc-architecture-in-ruby-on-rails-development-3l3g&psig=AOvVaw1Z6iJCaSbkY3Lz3pqcTTQg&ust=1705665334499000&source=images&cd=vfe&opi=89978449&ved=0CBUQjhxqFwoTCIjbqeHw5oMDFQAAAAAdAAAAABAM)
[Image: The Rails MVC architecture](https://www.google.com/imgres?imgurl=https%3A%2F%2Fwww.bogotobogo.com%2FRubyOnRails%2Fimages%2FMVC%2FMVC_Rails.png&tbnid=P0lZrIuP5EoIIM&vet=12ahUKEwiEwPCM7-aDAxXunCcCHZuVDn0QMygBegQIARBL..i&imgrefurl=https%3A%2F%2Fwww.bogotobogo.com%2FRubyOnRails%2FRubyOnRails_Model_View_Controller_MVC.php&docid=vVsErXgkKzjr6M&w=497&h=295&q=rails%20MVC%20architecture&ved=2ahUKEwiEwPCM7-aDAxXunCcCHZuVDn0QMygBegQIARBL)
https://stackoverflow.com/questions/11557719/rails-problems-with-index-view-on-nested-resources
https://github.com/kpfanning/mini-capstone
https://github.com/Daguilar94/clases_makeitreal
https://github.com/fiolarriviere/store2
https://github.com/aemabit/ror-7-base