๐Ÿ—๏ธ

MVC Pattern

Model-View-Controller โ€” The core architecture of Rails

MVC (Model-View-Controller) is a software design pattern and the foundation of Rails.

Model: Handles data and business logic. Maps 1:1 to database tables, allowing data manipulation via ActiveRecord without writing SQL. Validations, associations, and callbacks are also handled in the Model.

View: Handles the UI displayed to users. ERB (Embedded Ruby) templates embed Ruby code within HTML. Layouts and partials create reusable UI fragments.

Controller: The intermediary that receives HTTP requests, calls the appropriate Model, and passes results to the View. Handles authentication, authorization, and parameter processing.

Request flow in Rails: Browser โ†’ Router โ†’ Controller โ†’ Model (DB query) โ†’ Controller (pass data) โ†’ View (generate HTML) โ†’ Browser

Architecture Diagram

๐ŸŒ Browser โ€” GET /posts/1
Router
config/routes.rb
posts#show
๐Ÿ’Ž
Model
Post.find(1)
app/models/
๐ŸŽฎ
Controller
@post = Post.find
app/controllers/
๐Ÿ“„
View
<%= @post.title %>
app/views/
Controller Model (DB query) Controller (@post) View (HTML)
๐ŸŒ Browser โ€” HTML Rendering
Key point: <strong>Controller mediates between Model and View</strong> โ€” separation of concerns keeps code structure clear

Key Points

1

User requests URL from browser (e.g., GET /posts/1)

2

config/routes.rb maps URL to Controller#Action (posts#show)

3

PostsController#show executes โ€” @post = Post.find(params[:id])

4

Model (Post) queries data from DB via ActiveRecord

5

Controller passes @post instance variable to View

6

View (show.html.erb) renders @post data as HTML and returns to browser

Pros

  • Separation of concerns โ€” clear code structure
  • Easy team collaboration (designers=View, developers=Model)
  • Automatic mapping via Rails conventions
  • High code reusability

Cons

  • Overkill for simple apps
  • Controllers tend to bloat (Fat Controller)
  • Models can take on too many responsibilities (God Model)
  • Additional patterns like Service Objects may be needed

Use Cases

All Rails applications RESTful API servers Admin dashboards E-commerce sites