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
endWhat each tool does:
root— the route for/.redirect— answers straight from the router with a 301 by default (status: 302for temporary). No controller runs.constraints— a route only matches if the segment fits the pattern./books/abcnow finds no route and gets a 404.to:andas:— point any path at anycontroller#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".
The shortcut
For any URL request, ask "forward it, guard it, rename it, or group it?" Forward → redirect. Guard → constraints. Rename → path: or as:. Group → namespace.
Read the order
resources :booksis declared first, so itsGET /books/:idis tried first.
Drills
Answer fast — trust the rule.
What status does get "library", to: redirect("/books") send by default?
With constraints: { id: /\d+/ } on books, what happens to GET /books/latest?
namespace :admin do resources :books end sends /admin/books to which controller?
resources :members, path: "people" is declared. Which helper lists members?
Which line makes / show the book list?
Remember
- Routes match top to bottom; shape them, guard them, forward the old ones.
- Shortcut: forward, guard, rename or group.
- Trap: a general route above a specific one swallows it.
