Skip to content
Tutorials Center
My learning

Topics

Lesson 119 of 134 ยท Web and Ecosystem

Rails MVC, Routing and Controllers

Follow a Rails request from the browser to the response. Learn routes, resources, path helpers, controllers, filters, strong parameters and render versus redirect, with runnable stand-ins.

When you type a URL and press Enter, a surprising amount of code runs before a page appears. In Rails that journey is the same for every request, and once you can name each stop on it, the framework stops feeling like magic. The Rails overview introduced the big ideas and a toy MVC framework. This lesson goes deeper into the two pieces you touch most: the router, which decides which code handles a request, and the controller, which does the handling.

Rails is not installed on our runner and has no network, so the real files here are read-only. Wherever the behaviour is just Ruby, we rebuild it as a stand-in you can run: a resources route table with path helpers, and a controller with filters and strong parameters. Along the way you will use blocks, hashes and a little metaprogramming.

The life of a request

Every Rails request passes through the same pipeline. A web server such as Puma hands the request to Rack, the common interface from Sinatra and Rack. A stack of middleware wraps it (logging, sessions, cookies, security headers). Then the router picks a controller action, the action prepares data, and a view turns it into HTML.

sequenceDiagram
  participant B as Browser
  participant S as Puma and Rack middleware
  participant R as Router
  participant C as Controller
  participant M as Model
  participant V as View
  B->>S: GET /articles/7
  S->>R: request env
  R->>C: ArticlesController#show, params id=7
  C->>M: Article.find(7)
  M-->>C: article
  C->>V: render show
  V-->>B: 200 OK and HTML

One request from the browser to the response: the router chooses the action, the controller coordinates, the view renders.

Remember the roles. The model knows the data and the rules (ActiveRecord and Sequel Basics). The view knows how to display. The controller is the traffic officer between them. A healthy controller action is short: read input, call the model, choose a response.

Routes: from URLs to actions

All routes live in config/routes.rb. A route pairs an HTTP verb and a path pattern with a controller action.

Ruby
# config/routes.rb (read-only)
Rails.application.routes.draw do
  root "articles#index"

  get  "/about", to: "pages#about"
  post "/subscribe", to: "newsletters#create"

  resources :articles do
    resources :comments, only: [:create, :destroy]
  end
end

"articles#index" means "the index method of ArticlesController". The line resources :articles is a shortcut that creates seven routes for the standard actions at once. The word after the colon in a pattern such as /articles/:id is a dynamic segment: whatever appears there lands in the params hash.

Verb Path Action Path helper Purpose
GET /articles index articles_path list all
POST /articles create articles_path create one
GET /articles/new new new_article_path form for a new one
GET /articles/:id/edit edit edit_article_path form to change one
GET /articles/:id show article_path(id) show one
PATCH /articles/:id update article_path(id) change one
DELETE /articles/:id destroy article_path(id) remove one

This convention is called REST. The verb says what you want to do, and the path says which thing. Browsers can only send GET and POST from plain forms, so Rails hides the other verbs inside a form field named _method.

Run bin/rails routes in a real app to print the full table. Our stand-in below builds the same table, including nesting and the helper names, in about thirty lines.

Ruby A resources route table with path helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice two things in the output. First, /articles/new is recognized as articles#new, not as show with an id of "new", because the router tries routes in order and new comes first. The same rule applies in real Rails: the first matching route wins, so specific routes must come before general ones. Second, a nested route such as /articles/:article_id/comments/:id exposes both ids in params.

Path helpers

In real code you almost never type a path as a string. Use a helper instead: article_path(@article) gives /articles/7, and article_url(@article) gives the full address with host. If you later change the URL layout in routes.rb, every helper call adapts and nothing breaks. In a view, link_to "Edit", edit_article_path(@article) produces the link. An object passed to a helper is converted with to_param, which for models is the id.

You can add your own routes beyond resources. get "/search", to: "search#index", as: :search makes search_path, and constraints can restrict a segment, for example get "/year/:year", to: "archive#show", constraints: { year: /\d{4}/ }.

Controllers: input, work, response

A controller is a class whose public methods are actions. Rails creates a new controller object for each request, fills in params, session, cookies and request, and calls the action your route selected.

Ruby
# app/controllers/articles_controller.rb (read-only)
class ArticlesController < ApplicationController
  before_action :set_article, only: %i[show edit update destroy]

  def index
    @articles = Article.order(created_at: :desc).limit(20)
  end

  def show; end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article, notice: "Article created."
    else
      render :new, status: :unprocessable_entity
    end
  end

  private

  def set_article
    @article = Article.find(params[:id])
  end

  def article_params
    params.expect(article: [:title, :body])
  end
end

Three details deserve attention.

  • Instance variables become view variables. @articles is set in index and the template index.html.erb can read it. That is how data passes from controller to view.
  • No explicit render is needed. If an action finishes without rendering or redirecting, Rails renders the template with the same name as the action.
  • Private methods are not actions. Anything below private cannot be routed to, which is why helpers like set_article go there. See visibility.

Render or redirect

An action must end the request in one of two ways, and choosing correctly matters:

  • render builds a response now, using a template or text. Use it when a form fails validation, so the user sees their input and the error messages. Send the status :unprocessable_entity (422) so browsers and tools know the submit failed.
  • redirect_to sends a short response (status 302 or 303) that tells the browser to make a new request somewhere else. Use it after a successful change. This is the Post/Redirect/Get pattern: if the user presses reload, they repeat the harmless GET and not the POST that created the record.

Calling render or redirect_to twice in one action raises AbstractController::DoubleRenderError.

Filters and strong parameters

A filter is a method that runs around actions. The most used is before_action. It is a great place to load a record that several actions need or to require a login. If a before filter renders or redirects, the chain stops and the action never runs.

Strong parameters solve a security problem called mass assignment. Imagine Article.new(params[:article]) and a visitor who adds admin=true to the form. Without a guard, the model would accept it. Rails therefore raises an error when you pass unfiltered params to a model, and you must list what you allow: params.require(:article).permit(:title, :body) in older code, or params.expect(article: [:title, :body]) in recent Rails. Anything not listed is dropped. The security lesson returns to this.

This stand-in has a controller base class with before_action, render, redirect_to and a small strong-parameters object. Note how the second request is stopped by the login filter.

Ruby Filters, halting and strong parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Read the results one by one. The first request has no session, so require_login redirects and show never runs. The second works. The third finds no article, so set_article renders a 404 and halts. In the attack, the admin: true key is silently discarded by permit, so ARTICLES[1][:admin] stays false. The last call has no article key at all, so the guard raises ParameterMissing, which Rails turns into a 400 response.

Where to put logic

Beginners often pile code into controllers because it is the place where "things happen". Resist that. A simple guide:

  • Rules about data (validation, calculations, state changes) belong in models, or in plain Ruby objects next to them.
  • Display decisions (formatting, loops, markup) belong in views and helpers.
  • The controller only translates between HTTP and your application: params in, model call, response out.

A short controller is easy to read, and code that lives in a model can be tested without simulating a web request. The testing lessons (Minitest and RSpec) show how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does resources :articles give you?

    resources generates the seven RESTful routes (index, create, new, edit, show, update, destroy) and their path helpers. It does not create a table or templates.
  2. 2. A request matches two routes. Which one does Rails use?

    Routes are tried in the order they are defined and the first match wins, so put specific routes such as /articles/new before general ones.
  3. 3. A form submit fails validation. What should the controller do?

    Rendering keeps the user's input and error messages on screen. Redirect after success, render after failure.
  4. 4. What problem do strong parameters prevent?

    permit lists the fields that may reach the model. Extra fields such as admin=true are dropped instead of being assigned.
  5. 5. A before_action calls redirect_to. What happens to the action?

    When a before filter renders or redirects, Rails stops the chain and skips the action.

Summary

  • A request flows through the web server and Rack middleware, the router, a controller action and a view.
  • config/routes.rb maps verb plus path to controller#action; resources creates the seven standard routes and their *_path helpers, and the first matching route wins.
  • Controller actions are public methods; instance variables are shared with the view, and private methods are for helpers.
  • Redirect after a successful change; render with a 422 status after a failed one.
  • before_action filters share setup code and can halt the chain by rendering or redirecting.
  • Strong parameters (require/permit or expect) whitelist what may reach a model.
  • Keep controllers thin: put rules in models and display in views.

Next: Secure Ruby Code