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.