DEV Community

Cover image for 🚀 Ruby on Rails: MVC and you!
Dumebi Okolo
Dumebi Okolo

Posted on • Edited on

🚀 Ruby on Rails: MVC and you!

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

 1. The Pillars of the MVC architecture: Model, View, Controller

       1.1. The Model

             a. Data Representation

             b. Database Interactions

             c. Business Logic

       1.2. The View

             d. Templates

             e. Helpers

             f. Layout and Assets

       1.3. The Controller

             g. Actions

             h. Routing
 2. The Rails MVC architecture working together
 3. Benefits of the MVC Architecture
 4. References

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

Rails MVC architecture

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:



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


Enter fullscreen mode Exit fullscreen mode

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:



<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 %>


Enter fullscreen mode Exit fullscreen mode

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:



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


Enter fullscreen mode Exit fullscreen mode

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
Image: The Rails MVC architecture
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

Top comments (0)