MVC — Model, View, Controller
Open any Rails project and you will find three folders side by side: models, views and controllers. That is not tidiness for its own sake. It is the shape of every request Rails handles, and once you see it you can find your way around any Rails codebase.
The rule
Model knows the data, View shows it, Controller runs the errand.
- Model — a Ruby class for one kind of thing, like
Book. It reads and writes the database and holds the rules ("a book needs a title"). - View — a template that turns data into HTML. It should not decide anything important.
- Controller — receives the request, asks models for what it needs, and picks a view (or a redirect) as the answer.
A fourth piece sits in front: the router, which reads the method and path and chooses a controller action (a public method on the controller).
# app/controllers/books_controller.rb
class BooksController < ApplicationController
def show
@book = Book.find(params[:id]) # ask the model
end # then render show.html.erb
end<%# app/views/books/show.html.erb %>
<h1><%= @book.title %></h1>Instance variables such as @book are how the controller hands data to the view.
The shortcut
For any line of code, ask "is it data, display, or direction?" Data and rules go in the model, HTML goes in the view, and "which thing, then where next" goes in the controller.
Router
GET /books/7matches the books resource, so Rails callsBooksController#showwithparams[:id]set to"7".
The trap is the "fat controller": SQL fragments, pricing rules and HTML strings piled into actions. When a rule lives in the model, every controller that touches books gets it for free.
Drills
Answer fast — trust the rule.
Where should the rule "a review's rating must be between 1 and 5" live?
Which part chooses the controller action for an incoming request?
How does a controller action usually pass a book to its view?
Which part of MVC talks to the database?
Remember
- Model knows the data, View shows it, Controller runs the errand; the router picks the action.
- Shortcut: is this line data, display or direction?
- Trap: fat controllers — push rules down into models.
