skip to content

In config/routes.rb, how do optional segments, the (.:format) suffix and defaults: shape a route like get "archive/:year(/:month)"?

level: middleimportance: should knowfreq 35%

answer

  1. parentheses mark optional parts
  2. missing segment means nil param
  3. (.:format) appended by default
  4. format: false or true
  5. defaults: fills params

basics

~10 s

Parentheses make a segment optional, so archive/:year(/:month) matches /archive/2026 and /archive/2026/10; Rails appends an optional (.:format) unless format: false; defaults: supplies params a URL leaves out, such as format: "rss".

solid answer

~40 s

A route path is a pattern. `:year` is a dynamic segment, and parentheses mark an optional part: `get "archive/:year(/:month)", to: "stories#archive"` matches `/archive/2026` (no `params[:month]`) and `/archive/2026/10` (`params[:month] == "10"`). Rails appends an optional `(.:format)` to every route unless told otherwise, so `/archive/2026.rss` sets `params[:format] = "rss"`; `format: false` removes it and `format: true` makes it required. A dynamic segment stops at a dot by default, which is why `/stories/a.b` splits into `id: "a"` and `format: "b"`. `defaults:` fills params the URL does not carry: `defaults: { format: "rss" }` on a feed route, or a `defaults format: :json do ... end` block around a group.

code

ruby · 11 lines
ruby
# config/routes.rb
Rails.application.routes.draw do
  get "archive/:year(/:month)", to: "stories#archive", as: :archive
  get "feed", to: "stories#feed", defaults: { format: "rss" }
  get "stories/:id/embed", to: "stories#embed", format: false
end

# /archive/2026     -> params: { year: "2026" }
# /archive/2026/10  -> params: { year: "2026", month: "10" }
# /feed             -> params: { format: "rss" }
# /stories/42.json  -> no match for embed (format: false)

go deeper

for a junior

Read a pattern: static text, :name segments in params, parentheses for optional parts, and the (.:format) suffix on every route.

for a middle

Explain format: false and true, why dots split a segment into id and format, and how defaults: fills params per route or per block.

for a senior

Design URLs that stay stable, decide between optional segments and query strings, and switch the format suffix off where extensions must not change behaviour.

for a principal

Keep URL patterns consistent across the app so caching, links and integrations can rely on them.

## A route path is a pattern In `config/routes.rb` the string given to `get`, `post` or `match` is a **pattern** that a request path is matched against. Three kinds of piece appear in it: - **static text** such as `archive`, matched literally; - **dynamic segments** such as `:year`, matching one segment and arriving in `params`; - **optional groups** in parentheses, which may be present or absent as a whole. A newsroom CMS's archive shows a year, or one month of it: ```ruby get "archive/:year(/:month)", to: "stories#archive", as: :archive ``` | Request | `params[:year]` | `params[:month]` | |---|---|---| | `/archive/2026` | `"2026"` | absent | | `/archive/2026/10` | `"2026"` | `"10"` | | `/archive` | no match | no match | Optional groups can nest (`(/:month(/:day))`), and every captured value is a **string**. The helper fills only what you pass: `archive_path(2026)` gives `/archive/2026`, `archive_path(2026, 10)` gives `/archive/2026/10`. ## The (.:format) suffix Rails appends **`(.:format)`** to almost every route, which `bin/rails routes` shows in each pattern: 1. `/stories/42` reaches `show` with no `params[:format]`; the controller then renders its default format, HTML. 2. `/stories/42.json` reaches the **same** action with `params[:format] == "json"`. 3. `format: false` on a route (or a scope) **removes** the suffix, so `/stories/42.json` no longer matches it. 4. `format: true` makes the suffix **required**: the route matches only paths that end in an extension. Because the dot introduces the format, a dynamic segment's default pattern **stops at a dot**. A story slug such as `rails-8.1-released` therefore splits into `id: "rails-8"` and `format: "1-released"`, and the lookup fails. Allowing dots in a segment takes a segment constraint, which belongs to the constraints part of the DSL. ## defaults: `defaults:` sets params the URL does not carry: ```ruby get "feed", to: "stories#feed", defaults: { format: "rss" } defaults format: :json do get "stories/:id/stats", to: "stories#stats" end ``` - The feed route answers `/feed` with `params[:format] == "rss"`, so the action renders RSS without an extension in the URL. - The block form applies its defaults to every route inside it. - Any key works, not only `format`: `defaults: { section: "politics" }` gives `params[:section]` on that route. - A value present in the URL overrides the default, so `/feed.json` still sets `format` to `"json"`. ## Choosing between optional segments and query strings Optional segments suit **hierarchical** URLs whose parts read top-down (year, then month). Free-form filters, such as tags or sort orders, usually fit the query string better, where they need no route at all and arrive in `params` anyway. ## Common slips - **Typing captured values.** `params[:year]` is a string such as `"2026"`, and `params[:month]` is a string or missing; convert explicitly before comparing or querying by date. - **Forgetting the suffix exists.** An embed or webhook route that must not accept `.json` or `.xml` variants should say `format: false`, which makes the intent visible in the routes file. - **Expecting `format: false` to allow dots.** It only removes the suffix; the dynamic segment still stops at a dot, so slugs with dots need a segment constraint instead. - **Overusing optional groups.** Three or four optional levels make the helper's positional arguments hard to read; past two, separate named routes are usually clearer. ## Mistakes interviewers listen for | Belief | What Rails actually does | |---|---| | A missing optional segment arrives as `""` | The key is absent from `params` | | Numeric-looking segments arrive as integers | Every captured value is a string | | `format: false` makes the extension required | That is `format: true`; `false` removes the suffix | | `defaults:` overrides what the URL says | A value captured from the URL wins over the default |

  • Why does /stories/rails-8.1-released reach show with the wrong id?
    Every route ends in an optional `(.:format)`, and a dynamic segment's default pattern stops at a dot. The router therefore reads `id: "rails-8"` and `format: "1-released"`. Either avoid dots in slugs or give the segment a constraint that allows them. `format: false` alone does not help: the segment pattern still stops at a dot, so the path stops matching at all.
  • How does defaults: { format: "rss" } differ from writing /feed.rss links?
    With `defaults:` the plain `/feed` URL already arrives with `params[:format] == "rss"`, so feed readers can use an extension-free address. An explicit extension in the URL still wins over the default, so `/feed.json` would set `"json"`.

  • A missing optional segment arrives as an empty string
  • Captured segments arrive as integers when they look numeric
  • format: false makes the format extension required
  • A dynamic segment matches dots, so slugs with dots stay intact
  • defaults: overrides a format given in the URL