Skip to the workspace
Pebellslearn by building
Routing Fundamentals  ›  Capstone Project

Redirects, Constraints and Custom Routes

Redirects 15 minRoutes can send old URLs elsewhere with redirect, accept only matching segments with constraints, and be shaped with root, path, as, controller and namespace.

ruby on rails / Redirects, Constraints and Custom Routes

Explore each scene at your own pace.

01 · The rule

The rule

Redirects, Constraints and Custom Routes

Real apps collect URL wishes: the home page should show something useful, an old link from a newsletter must keep working, ids should be numbers, and the admin pages need their own area. All of these are routing options, no controller code required.

The rule

Routes match top to bottom; shape them, guard them, forward the old ones.

Rails.application.routes.draw do
  root "books#index"                                  # the home page, root_path

  get "library", to: redirect("/books")               # old URL, 301 permanent

  resources :books, constraints: { id: /\d+/ }        # ids must be digits

  get "books/:id/cover", to: "covers#show", as: :book_cover   # custom target and name

  resources :members, path: "people"                  # URL /people, helpers still members_path

  namespace :admin do
    resources :books                                  # /admin/books -> Admin::BooksController
  end
end

What each tool does:

  • root — the route for /.
  • redirect — answers straight from the router with a 301 by default (status: 302 for temporary). No controller runs.
  • constraints — a route only matches if the segment fits the pattern. /books/abc now finds no route and gets a 404.
  • to: and as: — point any path at any controller#action, and name it.
  • path: — change the URL text without changing the controller or helper names.
  • namespace — prefix the path, the helper names (admin_books_path) and the controller module (Admin::).

Rails tries routes in order and uses the first match. That is why a specific route such as get "books/export" must come above resources :books, or /books/export would be read as show with an id of "export".

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