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
GET /posts/1
config/routes.rb
Key Points
User requests URL from browser (e.g., GET /posts/1)
config/routes.rb maps URL to Controller#Action (posts#show)
PostsController#show executes โ @post = Post.find(params[:id])
Model (Post) queries data from DB via ActiveRecord
Controller passes @post instance variable to View
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