Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Meet Rails  ›  Lesson

MVC — Model, View, Controller

MVC architecture 12 minRails splits an app into models that hold data and rules, views that present it, and controllers that take each request and coordinate the other two.

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.

GET /books/7 through MVCStep 1 of 4
  1. Router

    GET /books/7 matches the books resource, so Rails calls BooksController#show with params[: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.

quick drill

Where should the rule "a review's rating must be between 1 and 5" live?

quick drill

Which part chooses the controller action for an incoming request?

quick drill

How does a controller action usually pass a book to its view?

quick drill

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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWho does what for one request?

A member opens GET /books/7 in Bookclub. Trace the request through the router, controller, model and view, saying what each part does and which part talks to the database.