The Model-View-Controller (MVC) architecture is a design pattern used in Ruby on Rails to separate the concerns of an application into three interconnected components. This separation helps in organizing code, making it more maintainable and scalable. In this section, we will explore each component of the MVC architecture and how they interact with each other.

  1. Understanding MVC Components

Model

  • Purpose: Represents the data and the business logic of the application.
  • Responsibilities:
    • Interacts with the database.
    • Validates data before saving it to the database.
    • Contains methods that define the business logic.
  • Example:
    class Article < ApplicationRecord
      validates :title, presence: true
      validates :content, presence: true, length: { minimum: 10 }
    end
    
    In this example, the Article model ensures that every article has a title and content with a minimum length of 10 characters.

View

  • Purpose: Represents the user interface of the application.
  • Responsibilities:
    • Displays data to the user.
    • Collects user input.
    • Contains HTML, CSS, and embedded Ruby (ERB) code.
  • Example:
    <!-- app/views/articles/show.html.erb -->
    <h1><%= @article.title %></h1>
    <p><%= @article.content %></p>
    
    This view template displays the title and content of an article.

Controller

  • Purpose: Acts as an intermediary between the Model and the View.
  • Responsibilities:
    • Receives user input from the View.
    • Interacts with the Model to process data.
    • Selects the appropriate View to render.
  • Example:
    class ArticlesController < ApplicationController
      def show
        @article = Article.find(params[:id])
      end
    end
    
    In this example, the show action in the ArticlesController retrieves an article from the database and makes it available to the view.

  1. How MVC Components Interact

Request Flow

  1. User Request: A user sends a request to the server (e.g., by clicking a link or submitting a form).
  2. Routing: The Rails router maps the request to a specific controller action.
  3. Controller Action: The controller action processes the request, interacts with the model, and prepares data for the view.
  4. View Rendering: The view renders the data and generates the HTML response.
  5. Response: The server sends the HTML response back to the user's browser.

Example Request Flow

  1. User Request: A user navigates to /articles/1.
  2. Routing: The router maps the request to the show action in the ArticlesController.
  3. Controller Action: The show action retrieves the article with ID 1 from the database.
  4. View Rendering: The show.html.erb view template displays the article's title and content.
  5. Response: The server sends the rendered HTML back to the user's browser.

  1. Practical Example

Let's create a simple Rails application to demonstrate the MVC architecture.

Step 1: Generate a Rails Application

rails new blog
cd blog

Step 2: Generate a Model

rails generate model Article title:string content:text
rails db:migrate

Step 3: Generate a Controller

rails generate controller Articles show

Step 4: Define Routes

Edit config/routes.rb to define the route for the show action:

Rails.application.routes.draw do
  resources :articles, only: [:show]
end

Step 5: Implement the Controller Action

Edit app/controllers/articles_controller.rb:

class ArticlesController < ApplicationController
  def show
    @article = Article.find(params[:id])
  end
end

Step 6: Create the View Template

Create app/views/articles/show.html.erb:

<h1><%= @article.title %></h1>
<p><%= @article.content %></p>

Step 7: Seed the Database (Optional)

Edit db/seeds.rb to add some sample data:

Article.create(title: 'First Article', content: 'This is the content of the first article.')
Article.create(title: 'Second Article', content: 'This is the content of the second article.')

Run the seed command:

rails db:seed

Step 8: Start the Rails Server

rails server

Navigate to http://localhost:3000/articles/1 to see the first article.

  1. Exercises

Exercise 1: Create a New Model and Controller

  1. Generate a new model called Comment with attributes author:string and body:text.
  2. Generate a controller called Comments with an action show.
  3. Define the route for the show action.
  4. Implement the show action to retrieve a comment by its ID.
  5. Create a view template to display the comment's author and body.

Solution

  1. Generate the model and controller:
    rails generate model Comment author:string body:text
    rails db:migrate
    rails generate controller Comments show
    
  2. Define the route in config/routes.rb:
    resources :comments, only: [:show]
    
  3. Implement the show action in app/controllers/comments_controller.rb:
    class CommentsController < ApplicationController
      def show
        @comment = Comment.find(params[:id])
      end
    end
    
  4. Create the view template app/views/comments/show.html.erb:
    <h2>Comment by <%= @comment.author %></h2>
    <p><%= @comment.body %></p>
    

Conclusion

In this section, we explored the MVC architecture, a fundamental design pattern in Ruby on Rails. We learned about the roles and responsibilities of the Model, View, and Controller components and how they interact to handle user requests. By following a practical example, we demonstrated how to create a simple Rails application using the MVC pattern. Understanding MVC is crucial for building well-structured and maintainable Rails applications. In the next section, we will dive into routing, which is essential for mapping user requests to controller actions.

© Copyright 2024. All rights reserved