Skip to the workspace
Pebellslearn by building
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.

ruby on rails / MVC — Model, View, Controller

Explore each scene at your own pace.

01 · The rule

The rule

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.