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.
- 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:
In this example, theclass Article < ApplicationRecord validates :title, presence: true validates :content, presence: true, length: { minimum: 10 } end
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:
This view template displays the title and content of an article.<!-- app/views/articles/show.html.erb --> <h1><%= @article.title %></h1> <p><%= @article.content %></p>
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:
In this example, theclass ArticlesController < ApplicationController def show @article = Article.find(params[:id]) end end
show
action in theArticlesController
retrieves an article from the database and makes it available to the view.
- How MVC Components Interact
Request Flow
- User Request: A user sends a request to the server (e.g., by clicking a link or submitting a form).
- Routing: The Rails router maps the request to a specific controller action.
- Controller Action: The controller action processes the request, interacts with the model, and prepares data for the view.
- View Rendering: The view renders the data and generates the HTML response.
- Response: The server sends the HTML response back to the user's browser.
Example Request Flow
- User Request: A user navigates to
/articles/1
. - Routing: The router maps the request to the
show
action in theArticlesController
. - Controller Action: The
show
action retrieves the article with ID 1 from the database. - View Rendering: The
show.html.erb
view template displays the article's title and content. - Response: The server sends the rendered HTML back to the user's browser.
- Practical Example
Let's create a simple Rails application to demonstrate the MVC architecture.
Step 1: Generate a Rails Application
Step 2: Generate a Model
Step 3: Generate a Controller
Step 4: Define Routes
Edit config/routes.rb
to define the route for the show
action:
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
:
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:
Step 8: Start the Rails Server
Navigate to http://localhost:3000/articles/1
to see the first article.
- Exercises
Exercise 1: Create a New Model and Controller
- Generate a new model called
Comment
with attributesauthor:string
andbody:text
. - Generate a controller called
Comments
with an actionshow
. - Define the route for the
show
action. - Implement the
show
action to retrieve a comment by its ID. - Create a view template to display the comment's author and body.
Solution
- Generate the model and controller:
rails generate model Comment author:string body:text rails db:migrate rails generate controller Comments show
- Define the route in
config/routes.rb
:resources :comments, only: [:show]
- Implement the
show
action inapp/controllers/comments_controller.rb
:class CommentsController < ApplicationController def show @comment = Comment.find(params[:id]) end end
- 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.
Ruby Programming Course
Module 1: Introduction to Ruby
Module 2: Basic Ruby Concepts
Module 3: Working with Collections
Module 4: Object-Oriented Programming in Ruby
- Classes and Objects
- Instance Variables and Methods
- Class Variables and Methods
- Inheritance
- Modules and Mixins
Module 5: Advanced Ruby Concepts
Module 6: Ruby on Rails Introduction
- What is Ruby on Rails?
- Setting Up Rails Environment
- Creating a Simple Rails Application
- MVC Architecture
- Routing
Module 7: Testing in Ruby
- Introduction to Testing
- Unit Testing with Minitest
- Behavior-Driven Development with RSpec
- Mocking and Stubbing