skip to content

Constraints & Redirects

Constraints restrict a route by a segment regex, the subdomain or a lambda or object with matches?, while redirect() and glob segments catch legacy URLs. Interviewers probe catch-alls and 301s.

part ofRuby on Railsread it →
on this pageshow

explore

questions

4

In config/routes.rb, how do you restrict a :year segment to four digits, and why does Rails reject ^ or \A in that regex?

level: middleimportance: must knowfreq 52%

answer

  1. a regexp per segment name
  2. constraints: hash or bare key shorthand
  3. whole segment must match anyway
  4. ArgumentError when routes load
  5. no match means the next route

basics

~20 s

Give the segment a regexp, as in constraints: { year: /\d{4}/ } or the shorthand year: /\d{4}/. Rails matches it against the whole segment already, so ^, \A, $ or \z raise an ArgumentError when the routes load.

solid answer

~40 s

In `config/routes.rb` you write `get "journal/:year", to: "journal#archive", constraints: { year: /\d{4}/ }`, or pass `year: /\d{4}/` directly as a route option. The regexp becomes a requirement inside the route's path pattern, and that pattern is anchored at both ends, so the segment must match in full: `/journal/2019` matches, `/journal/19` and `/journal/2019x` do not. Because the anchoring is built in, Rails refuses `^`, `\A`, `$`, `\z` or `\Z` at the edges of the regexp and raises `ArgumentError` ("Regexp anchor characters are not allowed in routing requirements") at boot. A request that fails the constraint is not an error inside the route: the route simply does not match, and the router tries the later routes before answering 404. The same requirement also guards URL generation, which raises `ActionController::UrlGenerationError` for a value that does not fit.

code

ruby · 8 lines
ruby
# config/routes.rb
Rails.application.routes.draw do
  get "journal/:year", to: "journal#archive", as: :journal_archive,
    constraints: { year: /\d{4}/ }

  # raises ArgumentError when the routes load:
  # get "journal/:year", to: "journal#archive", constraints: { year: /^\d{4}$/ }
end

go deeper

for a junior

Recall the two spellings, constraints: { year: /\d{4}/ } and year: /\d{4}/, and that anchors are not allowed.

for a middle

Explain that the route pattern is anchored as a whole, that anchors raise ArgumentError at boot, and that a failed constraint just means the route does not match.

for a senior

Use constraints to let several routes share one path shape instead of relying on line order, and expect UrlGenerationError when code builds a link that breaks one.

for a principal

Treat routing constraints as a shape filter, not validation or authorization, and keep business rules in controllers where they can be tested and reported.

## What a segment constraint is A **dynamic segment** is a placeholder such as `:year` or `:id` in a route's path. By default it matches any run of characters except a slash, a dot or a question mark, so `get "journal/:year"` happily accepts `/journal/2019`, `/journal/latest` and `/journal/abc`. A **segment constraint** narrows that with a Ruby regexp keyed by the segment's name. In the wedding-planner app the old journal archive lives at `/journal/2019`, and only four-digit years should reach the archive action: ```ruby # config/routes.rb get "journal/:year", to: "journal#archive", constraints: { year: /\d{4}/ } # shorthand: a Regexp option keyed by a path segment is a constraint get "journal/:year", to: "journal#archive", year: /\d{4}/ # block form: one rule for several routes constraints(year: /\d{4}/) do get "journal/:year", to: "journal#archive" get "journal/:year/:slug", to: "journal#show" end ``` The `resources` macro takes the same option for its implicit `:id`: with `resources :guests, constraints: { id: /\d+/ }`, a later `get "guests/export"` is no longer swallowed by the `show` route, because `export` fails the digits rule and the router moves on. ## Why anchors are refused Rails compiles the whole route into one **path pattern**, and that pattern is anchored at the start and the end of the path. Each segment regexp is embedded at the segment's position, so it already has to match the **entire** segment and nothing more. An explicit anchor would be redundant at best and would break the compiled pattern at worst, so the mapper checks every requirement while the routes load: - `^` or `\A` at the start of the regexp source, or `$`, `\z` or `\Z` at the end, raises `ArgumentError` with the message "Regexp anchor characters are not allowed in routing requirements". - The **multiline** flag (`/m`) raises too, except on a glob segment, where Rails itself uses one. - Both checks run when the **routes file is loaded**, not per request, so a bad constraint fails loudly before any guest sees it. The fix is simply to drop the anchors: `/\d{4}/` already means "exactly four digits" in a route. ## What happens when a request fails the constraint A constraint is part of matching, not a validation inside the action: 1. The request `/journal/latest` comes in. 2. The archive route's pattern does not match, because `latest` fails `/\d{4}/`. 3. The router keeps looking at the routes declared after it. 4. If nothing else matches, the request ends as a routing error, which a production app answers with 404. That makes constraints a tool for **sharing a path shape** between routes. The routing guide's own example sends paths that start with a digit to articles and everything else to user profiles: ```ruby get "/:id", to: "articles#show", constraints: { id: /\d.+/ } get "/:username", to: "users#show" ``` ## Constraints work in both directions The same requirement guards **URL generation**. With the route named `as: :journal_archive`, calling `journal_archive_path(year: "latest")` does not build a bad link; it raises `ActionController::UrlGenerationError`, and the message lists the possible unmatched constraints. That is usually what you want: a broken link fails in tests instead of in a guest's browser. ## Common adjustments | Need | Constraint | |---|---| | Digits only | `id: /\d+/` | | Four-digit year | `year: /\d{4}/` | | Allow dots in a segment (an email-like slug) | `slug: /[^\/]+/` | | Upper-case code like `A12345` | `code: /[A-Z]\d{5}/` | The dot case matters because the default segment rule stops at a dot, which is how `(.:format)` gets its value. A slug like `ana.ben` therefore needs an explicit constraint that allows dots, and the format then has to be given another way or disabled. ## Limits of a regexp constraint - It sees **one segment as a string**; it cannot check that the year exists in the database or that a slug belongs to a couple. That logic belongs in the controller, or in a request-based constraint object when it must decide routing. - It does not convert types: `params[:year]` is still the string `"2019"`. - It is not input validation for security; the controller still treats every param as untrusted. - It covers only the segment it names. On `resources :guests, constraints: { id: /\d+/ }` the rule guards `:id` on the member routes, while a nested parent key such as `:guest_id` needs its own entry. - It is case-sensitive unless the regexp says otherwise, so `/[a-z]+/` rejects `Venue`. Used this way, a segment constraint is a cheap, declarative guard that keeps junk paths away from actions and lets several routes share one URL shape.

  • In config/routes.rb, how do you let an :id segment contain dots, such as ana.ben?
    The default segment rule excludes dots because the dot introduces the optional `(.:format)` part. Add a constraint that allows them, such as `constraints: { id: /[^\/]+/ }`, which accepts anything except a slash. After that the dot no longer separates a format, so a request for `ana.ben.json` puts the whole string into `params[:id]` unless you disable or restructure the format segment.
  • What does a Rails path helper do when you pass it a value that breaks the route's segment constraint?
    It refuses to build the URL. Generation checks the same requirements as recognition, so `journal_archive_path(year: "latest")` raises `ActionController::UrlGenerationError`, and the message names the possible unmatched constraints. That turns a bad link into a test failure instead of a broken page.

  • You must write ^ and $ or the regexp will match part of the segment
  • A failed segment constraint makes the action raise a validation error
  • Constraints turn params[:year] into an Integer for the controller
  • A segment constraint can check that the year exists in the database
  • Constraints are checked only when matching requests, never when generating URLs
open as a page

In config/routes.rb, how do you send old /journal/2019/our-venue URLs to new paths with redirect(), and which status does it send by default?

level: juniorimportance: should knowfreq 45%

basics

~10 s

Point the old route at redirect(), as in get "journal/:year/:slug", to: redirect("/stories/%{year}/%{slug}"). It answers 301 Moved Permanently unless you pass status:, and the string form drops the old query string.

open as a page

In a Rails wedding-planner app where each couple gets a subdomain like anna-and-ben.example.com, how do you route those requests with request constraints and a matches? object?

level: seniorimportance: should knowfreq 34%

basics

~10 s

Wrap the couple routes in constraints(CoupleSubdomain) do ... end, where CoupleSubdomain.matches?(request) checks request.subdomain. A false answer makes the router fall through to the marketing routes declared below.

open as a page

In config/routes.rb, how do you write a *path catch-all route, and why can it break Active Storage URLs if added carelessly?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Add match "*path", to: "errors#not_found", via: :all as the last route. Engine routes such as Active Storage's /rails/active_storage/... are drawn after the app's file, so the catch-all shadows them unless a lambda constraint excludes /rails/.

open as a page