Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 37 ยท Routing and Controllers

Routing Basics

Learn how config/routes.rb maps URLs to controller actions in Rails: get and post routes, dynamic segments, constraints, root, redirects and named route helpers, with a runnable matcher stand-in.

The router is the front door of a Rails app. It reads the request's HTTP verb and path, looks through a list of rules in config/routes.rb, and picks the controller action that should answer. If no rule matches, Rails responds with 404 Not Found.

In this lesson you will write the basic kinds of routes: static paths, dynamic segments such as /articles/42, optional parts, constraints, redirects and the root route. You will also meet named route helpers like articles_path, which keep URLs out of your templates. The real routes file is read-only here. To make the matching visible, we build a small route matcher in plain Ruby that works like the real one.

The routes file

Ruby
# config/routes.rb  (read-only)
Rails.application.routes.draw do
  get "about", to: "pages#about"
  get "contact", to: "pages#contact"
  post "subscribe", to: "newsletters#create"
  root "pages#home"
end

Rails.application.routes.draw takes a block. Inside it, each line is a method call such as get, post or root. The format of the target is "controller#action": "pages#about" means the about method of PagesController. Routes are checked top to bottom and the first match wins, so order matters.

HTTP verbs

Each verb has its own method. They match both the verb and the path.

Method Verb Typical use
get GET Show a page
post POST Create something, submit a form
patch / put PATCH / PUT Update
delete DELETE Remove

Browsers can only send GET and POST from a plain link or form. For the others, Rails forms include a hidden _method field and Rails treats the request as PATCH or DELETE. You will see this in forms.

Dynamic segments

A segment starting with a colon is a placeholder. Whatever is in the URL at that spot becomes a param.

Ruby
# read-only
get "articles/:id", to: "articles#show"
# GET /articles/42     -> params[:id] == "42"

get "authors/:author_id/articles/:id", to: "articles#show"
# GET /authors/7/articles/42 -> params[:author_id] == "7", params[:id] == "42"

Params are always strings. Convert with to_i if you need a number, or let Active Record do it with Article.find(params[:id]). Placeholders match anything except / and . by default.

You can make a part optional with parentheses and add a glob that matches the rest of the path:

Ruby
# read-only
get "posts(/:page)", to: "posts#index"        # /posts and /posts/2
get "files/*path", to: "files#show"           # /files/a/b/c.txt -> params[:path] == "a/b/c"

Constraints and defaults

A constraint restricts what a segment may match. That lets you tell /articles/42 (an id) from /articles/new (a different page):

Ruby
# read-only
get "articles/:id", to: "articles#show", constraints: { id: /\d+/ }
get "reports/:year", to: "reports#index", constraints: { year: /\d{4}/ }
get "feed", to: "articles#index", defaults: { format: "rss" }

defaults fills in params when the URL does not provide them.

Root, redirects and the catch-all

Ruby
# read-only
root "pages#home"                        # GET /
get "old-about", to: redirect("/about")  # 301 redirect
get "home", to: redirect("/")
get "*unmatched", to: "errors#not_found" # last-resort catch-all

redirect is handled by the router itself and never reaches a controller. A catch-all must be the last route, since routes match top to bottom.

Named routes

Give a route a name with as:. Rails then builds two helpers: name_path (a path like /about) and name_url (a full URL with the host).

Ruby
# read-only
get "about", to: "pages#about", as: :about
# about_path => "/about"
# about_url  => "http://localhost:3000/about"

get "articles/:id", to: "articles#show", as: :article
# article_path(42) => "/articles/42"

Use _path in views and _url in redirects and emails. Never hard-code "/about" in a template: if the route changes, the helper changes with it. Inspect names with bin/rails routes.

Stand-in: a route matcher

This stand-in implements the core algorithm: compile each pattern to a regular expression, try them in order, and extract params. It also builds paths from names, like route helpers.

Ruby Stand-in: matching verbs, paths and dynamic segments

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.

Note two details: /articles/new matches before /articles/:id because it is listed first, and /articles/abc is a 404 because the \d+ constraint rejects it. The GET /subscribe is a 404 because only a POST route exists.

Stand-in: building URLs from names

Route helpers are the reverse of matching. Instead of "/articles/#{id}" scattered around, one name produces the path. If the URL scheme changes, only the route changes.

Ruby Stand-in: named helpers as methods

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.

This uses define_method: Rails creates article_path and article_url dynamically in much the same way.

Run bin/rails routes -g article to grep the route table. When a page returns 404 or "No route matches", the table is the first place to look.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In get "articles/:id", to: "articles#show", what is params[:id] for GET /articles/42?

    Params from the URL are always strings. Convert with to_i or let find do it.
  2. 2. Two routes could match the same URL. Which one runs?

    Routes are checked top to bottom and the first match wins.
  3. 3. What does as: :about give you?

    Named routes generate _path and _url helper methods.
  4. 4. Where should a catch-all route like get "*unmatched" go?

    It matches everything, so it must come after all other routes.

Summary

  • config/routes.rb maps a verb and path to "controller#action"; first match wins.
  • :name segments become string params; (...) marks optional parts and *path globs the rest.
  • constraints restricts segments and defaults fills missing ones.
  • root, redirect and a final catch-all handle the home page, moved URLs and 404s.
  • as: creates _path and _url helpers; use them instead of hard-coded URLs.

Next: Resourceful Routes