The most popular of these frameworks in web development are Ruby on Rails, or simply called Rails. This is known for its simplicity and convention over configuration and also the extensive use of the MVC (Model-View-Controller) architecture. That architecture is the backbone upon which Ruby on Rails applications are structured in order to create clean, maintainable, and scalable web applications.
In this blog, we will dive into the MVC architecture in Ruby on Rails and understand how it works along with all its components and how they interact to form a comprehensive web application.
What is MVC Architecture?
MVC architecture is a design pattern that divides an application into three interconnected components:
- Model : It manages the data and the business logic of the application.
- View: It deals with the task of rendering the data (usually in HTML format) to the user.
- Controller: It is treated as glue for both the Model and the View because it will receive input from the user, update the model, and also update the view.
This results in having application aspects separated from each other, easier maintenance, extension, and debugging.
The Three Components of MVC in Ruby on Rails
1. Model (M)
Rails Model contains business logic and data of the application. Models can be written to represent data or entities in the application and declare rules about the data. They have direct interaction with the database; they also validate data; and connect different objects in data.
Key Points
The basic role of the model is to query a database, fetch records, and store data. Models work with the business logic, validating data, for instance, or checking the user's email so that it should be unique.
- Rails makes use of the ActiveRecord layer, which is an Object-Relational Mapping (ORM) layer, meaning it can connect models with database tables, letting you use Ruby code instead of SQL to interact with your database.
Example:
ruby
class Post < ApplicationRecord
validates :title, presence: true
has_many :comments
end
Here, the Post
model is the posts table in the database, and is responsible for logic applied directly toward posts.
- View (V)
The View concerns the presentation layer of an application. This view takes data from a model, probably fed in through the controller, and then presents it to the user. Most views in Rails are written in HTML with embedded Ruby code, known as ERB, that can embed the dynamic content.
Points to Remember
Views do not have to concern themselves with any business logic; they are strictly for display purposes.
- Rails encourages the use of partials to split views up into reusable modules so that your code is more modular and easier to manage. You can also include helper methods if you need to format data or any other presentation-related operations.
Example:
erb
<!-- app/views/posts/show.html.erb -->
<h1><%= @post.title %></h1>
<p><%= @post.body %></p>
This view displays the title and body for a post. The data (@post.title
and @post.body
) will be passed from the controller to the view.
3. Controller (C)
Thus, the Controller will play the role of go-between
between the Model and the View. Controllers respond to user inputs- usually, HTTP requests-that translate into retrieving appropriate data from a model and sending the relevant view the appropriate data with which to work. The Controllers also contain logic that ties user actions to updates of models.
Key Points:
The function of a Controller is to govern the path of data and determine the view to be rendered or the model to be updated.
- Accept HTTP requests from the browser and return HTTP responses - HTML, JSON, etc.
- In rails; Controllers are inherited from ActionController::Base
In this situation, PostsController
is an instance that fetches the post from the database, whereas the Post
model is used to fetch it. Then it passes it on to the view to render.
The show
action handles one post by its ID, which is retrieved from the URL.
The MVC Flow in Rails
Here's how the typical request-response cycle works in a Ruby on Rails application using the MVC architecture:
User Makes a Request: A user clicks on the link or submits a form. This action generates an HTTP request.
Controller Handles the Request: The request takes one to the appropriate controller action. The controller retrieves any data from the model that are needed to accomplish the request and processes the request itself.
Model Retrieves Data: In case the controller needs data from the database, for example, retrieve a list of posts, it calls the methods from the model in order to access or modify data.
Controller Passes Data to the View: When the controller has acquired all of the relevant data, it passes the data to the view for rendering.
The View Renders the Data: The view receives data and renders it to HTML (or JSON, XML, etc.), which is then returned as a response back to the browser.
Also Read:
Django vs Ruby on Rails: Which Framework Should You Choose?
The Ultimate Roadmap to Mastering Data Structures and Algorithms (DSA)
Exploring Ubuntu: Features and Benefits of This Popular Linux Distribution
Example: MVC Flow in Ruby on Rails
Let's follow a simple example. Suppose a user requests to visit a certain URL, and they see a blog post:
- The User request is
http://yourapp.com/posts/1
. - The Rails router connects the URL above to the
show
action in thePostsController
. - The
PostsController
retrieves the post withid = 1
from the database using thePost
model (@post = Post.find(1)
) - The controller then passes the
@post
object to theshow.html.erb
view. - That view renders the
title
andbody
of the post, and the browser displays it to the user.
Advantages of MVC Architecture in Rails
Separation of Concerns : The role of all the components of the MVC is well defined; hence, the codebase becomes understandable and easy to maintain.
Modularity: Since Model, View, and Controller are separated, there is no effect on other components while changing any one among them.
Reusability: Views and controllers are reusable across any application of an application without writing redundant code.
Scalability: MVC encourages a scalable architecture through the separation of code to clean, isolated parts. This is particularly well-suited for expanding applications
In Ruby on Rails, MVC architecture makes for a clean and structured approach to the development of web applications. It splits an application into three distinct components: Model, View, and Controller, which, in turn, make development more efficient, scalable, and maintainable. Knowing how to use MVC is crucial in effective application building with Ruby on Rails, developing anything from a simple blog or even more complex web applications.
With Rails using MVC, you'll not only end up writing quality code but will be in a position to work with large teams, use complex projects, and keep your applications well-organized. Happy coding!