skip to content

Route Mapping DSL

The config/routes.rb DSL maps each URL and verb to a controller action: resources and nesting, custom routes, constraints and path helpers. Interviewers probe RESTful design and match order.

part ofRuby on Railsread it →
on this pageshow

explore

questions

27

In Rails, what is the difference between a named route's _path and _url helpers, and when do you need the _url form?

level: juniorimportance: must knowfreq 72%

answer

  1. same route name, two suffixes
  2. relative path vs scheme plus host
  3. host comes from the current request
  4. links that leave the page
  5. extra keys become the query string

basics

~10 s

Both come from the same route name: class_session_path(@session) returns "/class_sessions/42", class_session_url(@session) adds scheme, host and port. Use _url whenever the link leaves the current page: emails, calendar invites, API payloads, feeds.

solid answer

~40 s

Every named route gets two helpers built from its name, the Prefix column in `bin/rails routes`. `class_session_path(@session)` returns a path such as `/class_sessions/42`; `class_session_url(@session)` returns `https://studio.example/class_sessions/42`. Inside a request, the `_url` helper takes protocol, host and port from the current request, overridden by any `default_url_options`. Use `_path` for links inside your own pages, where the browser resolves it against the current host. Use `_url` wherever the string is read outside that page: an exported calendar invite, an email, a JSON payload another service stores, a canonical link. Both accept a record or an id for the dynamic segments, and extra keys become the query string, so `class_sessions_path(level: "beginner")` gives `/class_sessions?level=beginner`.

code

ruby · 9 lines
ruby
# config/routes.rb: resources :class_sessions
class_session_path(@session)
# => "/class_sessions/42"
class_session_url(@session)
# => "https://studio.example/class_sessions/42" (host from the request)
class_sessions_path(level: "beginner")
# => "/class_sessions?level=beginner"
class_session_url(@session, anchor: "booking", protocol: "https")
# => "https://studio.example/class_sessions/42#booking"

go deeper

for a junior

Recall that both helpers come from one route name, _path is relative and _url carries scheme and host, and extra keys become the query string.

for a middle

Explain where the _url host comes from during a request and why a job or rake task has no such source.

for a senior

Decide per output channel: paths inside pages, absolute URLs for invites, emails, payloads and canonical links, with protocol and host configured per environment.

for a principal

Set a team rule for which layers may build absolute URLs and where the canonical host lives, so multi-domain or white-label setups stay correct.

## One route, two helpers When a route has a name, Rails defines a pair of helper methods from it. The name is what `bin/rails routes` prints in the **Prefix** column; the helpers add a suffix: | Helper | Returns | Example | |---|---|---| | `class_session_path(@session)` | path only | `/class_sessions/42` | | `class_session_url(@session)` | scheme, host, port and path | `https://studio.example/class_sessions/42` | The helpers are available in controllers, views and helpers out of the box, and anywhere else through `Rails.application.routes.url_helpers`. ## What the arguments do Both helpers take the same arguments: - **Positional values** fill the dynamic segments in order. A record is turned into its segment with `to_param`, so `class_session_path(@session)` and `class_session_path(42)` both work. - **A hash** can name segments explicitly: `class_session_path(id: 42)`. - **Extra keys** that are not segments become the **query string**: `class_sessions_path(level: "beginner")` returns `/class_sessions?level=beginner`. - Special keys shape the URL instead: `anchor: "booking"` adds `#booking`, `format: :ics` adds `.ics` when the route has a format segment, and on the `_url` form `host:`, `protocol:` and `port:` override those parts. ## Where the _url host comes from Inside a controller action or a view rendered by one, Rails builds the URL options from the **current request**: its host, port and protocol. Anything you set in `default_url_options` is merged on top, and options passed to the helper win over both. So during a request to `https://studio.example`, `class_session_url(@session)` needs nothing more. Outside a request (a background job, a rake task, a model method) there is no request to ask. The `_url` helpers then need a configured host or an explicit `host:` option, and without one they raise `ArgumentError` with the message "Missing host to link to!". ## Choosing between them Use **`_path`** when the link is rendered into a page of your own app: - the browser resolves it against the page's own host, so it works on every domain, port and environment without configuration; - it is shorter and avoids baking a host into cached HTML. Use **`_url`** when the string will be read somewhere that has no current page: 1. **Calendar invites.** The yoga studio exports `.ics` files whose event `URL` must open the class page from a phone's calendar app; a bare path means nothing there. 2. **Emails** and other messages read in a different client. 3. **API payloads and webhooks** that another system stores or follows later. 4. **Canonical and social-preview links**, feeds and sitemaps, which crawlers expect to be absolute. A quick test: if the string could be copied out of the page and still has to work, it needs the host, so use `_url`. ## Common mistakes - **Absolute links built from a request in a job.** A job that renders `class_session_url` has no request; configure the host instead of passing request data into the job. - **Hard-coding the host** in a string (`"https://studio.example" + class_session_path(s)`). It drifts between environments and ignores the configured protocol and port. - **Using `_path` in exported data.** A path in an invite or a JSON payload breaks the first time it is read outside the browser tab. - **Expecting `_url` to fix the protocol.** It uses the request's protocol, or `http` when none is known and no `protocol:` option is set; a production default of `https` must be configured. ## In tests Integration tests make requests against a default host of `www.example.com`, so a `_url` helper called from the test or from the app during that request returns `http://www.example.com/class_sessions/42`. Two habits keep assertions stable: - compare **paths** with `_path` helpers in redirect and link assertions, so the host never matters; - where the absolute form is the point (an invite payload, a canonical tag), assert the **configured** host explicitly, because that is exactly what breaks between environments. A test that only ever checks paths will not notice a missing production host, which is why exports deserve one absolute-URL assertion of their own. ## Seeing the names If you are unsure what a helper is called, read the Prefix column of the route table, or call it in the console through `Rails.application.routes.url_helpers.class_sessions_path`. A route with no name in the Prefix column has no helpers at all; give it one with `as:`.

  • Why do Rails _url helpers work in a controller without any host configuration?
    During a request, the controller's `url_options` start from the request's host, port and protocol and then merge `default_url_options` on top. The `_url` helper therefore copies the host the visitor actually used. Outside a request that source is missing, so a job or rake task needs a configured host or an explicit `host:` option.
  • In Rails, what does class_sessions_path(level: "beginner", page: 2) return for resources :class_sessions?
    It returns `/class_sessions?level=beginner&page=2`. The index route has no dynamic segments to fill, so every key that is not a segment, or a reserved option such as `anchor:` or `format:`, is appended as a query parameter.

  • _path helpers are only for views and _url helpers only for controllers
  • A _path is fine in an exported calendar invite because calendars resolve it
  • _url helpers always use https in production without configuration
  • Extra hash keys passed to a path helper raise an ArgumentError
  • Outside a request, _url helpers fall back to localhost:3000
open as a page

In Rails, how do you list an app's routes with bin/rails routes, and what do its -c, -g and --expanded options do?

level: juniorimportance: must knowfreq 62%

basics

~20 s

bin/rails routes prints every route in match order as Prefix, Verb, URI Pattern and Controller#Action. -c filters by controller, -g greps names, verbs, paths and actions (or a concrete URL), and --expanded prints one block per route.

open as a page

In config/routes.rb, which routes, helper names and params does resources :episodes nested inside resources :shows produce?

level: juniorimportance: must knowfreq 72%

basics

~10 s

Nesting puts /shows/:show_id in front of all seven episode routes, prefixes the helpers (show_episodes_path(show), show_episode_path(show, episode)), passes params[:show_id] next to params[:id], and still dispatches to a plain EpisodesController.

open as a page

In config/routes.rb, which seven routes does resources :photos generate, with their HTTP verbs, paths, controller actions and named helpers?

level: juniorimportance: must knowfreq 85%

basics

~10 s

resources :photos draws index and create on /photos, new on /photos/new, and show, edit, update and destroy on /photos/:id, all handled by PhotosController, with helpers photos_path, new_photo_path, edit_photo_path and photo_path.

open as a page

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%

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.

open as a page

In config/routes.rb, how do member and collection routes added to resources :stories differ in path, params and helper name?

level: middleimportance: must knowfreq 65%

basics

~10 s

A member route acts on one story, so post :publish inside member gives POST /stories/:id/publish with params[:id] and publish_story_path(story); a collection route acts on the set, so get :drafts gives GET /stories/drafts and drafts_stories_path.

open as a page

In config/routes.rb, how do namespace :admin, scope module: :admin, scope path: and scope as: differ in URL, helper name and controller class?

level: middleimportance: must knowfreq 60%

basics

~10 s

namespace :admin prefixes the URL (/admin/stories), the helpers (admin_stories_path) and the controller (Admin::StoriesController) at once; scope module: changes only the class, scope path: only the URL, and scope as: only the helper names.

open as a page

In a Rails bike-share app, why does GET /bikes/nearby hit BikesController#show and answer 404 when get "bikes/nearby" is declared after resources :bikes?

level: middleimportance: must knowfreq 55%

basics

~10 s

Rails tries routes in declaration order and stops at the first match. resources :bikes already defines GET /bikes/:id, whose :id accepts "nearby", so show runs, Bike.find("nearby") raises RecordNotFound and production answers 404.

open as a page

In config/routes.rb, how do only: and except: trim resources :photos, and what happens to a request for an action you removed?

level: middleimportance: must knowfreq 62%

basics

~20 s

only: keeps the listed actions and except: drops them; the removed routes and their helpers are simply not drawn. A request for a removed route raises ActionController::RoutingError (404), unless another route, such as GET /photos/:id, matches it first.

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 config/routes.rb, how do root, get with to: "stories#preview" and match with via: map one-off URLs, and how are those routes named?

level: juniorimportance: should knowfreq 55%

basics

~10 s

root "stories#index" maps GET / and defines root_path; get "stories/:id/preview", to: "stories#preview", as: :preview_story maps one verb and path to an action; match does the same for several verbs and raises ArgumentError without via:.

open as a page

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%

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".

open as a page

In Rails, how do polymorphic_path and url_for build a URL from a record, a class or an array like [@studio, @session]?

level: middleimportance: should knowfreq 46%

basics

~20 s

polymorphic_path turns the object into a named-route helper call: a persisted record maps to its singular route (class_session_path), a new record or class to the collection, and an array to a nested name such as studio_class_session_path(@studio, @session).

open as a page

In an Active Record model, how does to_param decide the :id that Rails URL helpers generate, and how do you produce /class_sessions/42-sunrise-flow?

level: middleimportance: should knowfreq 40%

basics

~20 s

URL helpers call to_param on a record, which returns its id as a string. Declaring to_param :title in the model (or overriding the method) yields "42-sunrise-flow", and ClassSession.find still works because the leading digits cast to 42.

open as a page

In a Rails test, what do assert_recognizes, assert_generates and assert_routing each check about a route, and when would you use each?

level: middleimportance: should knowfreq 32%

basics

~10 s

assert_recognizes checks that a path (and verb) routes to the expected controller, action and params; assert_generates checks that those options build the expected path; assert_routing checks both directions at once.

open as a page

In config/routes.rb, how do concern and concerns: let shows and episodes share the same nested reviews routes?

level: middleimportance: should knowfreq 30%

basics

~10 s

concern :reviewable do resources :reviews end defines a reusable block of routes; resources :shows, concerns: :reviewable (or concerns :reviewable inside the block) draws those nested reviews routes under each resource that names it.

open as a page

In config/routes.rb, what do the path:, as:, controller:, param: and path_names: options each change on resources :photos?

level: middleimportance: should knowfreq 40%

basics

~20 s

path: changes the URL prefix, as: changes the helper names, controller: changes the controller class, param: renames the :id segment and params key, and path_names: renames the new and edit URL segments; each leaves the others untouched.

open as a page

In config/routes.rb, how does resource :profile differ from resources :profiles in routes, helpers and the controller it calls?

level: middleimportance: should knowfreq 55%

basics

~20 s

resource :profile draws six routes on /profile with no :id and no index, names helpers profile_path, new_profile_path and edit_profile_path, and still routes to the plural ProfilesController; the action finds the record from context, not params.

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

When a Rails job builds absolute class links for exported calendar invites, why does class_session_url raise Missing host, and where should the host come from?

level: seniorimportance: should knowfreq 38%

basics

~10 s

A job has no request, and Rails.application.routes.url_helpers only knows the routes' own default_url_options, empty by default, so _url helpers raise ArgumentError. Set Rails.application.routes.default_url_options with host and protocol per environment.

open as a page

What does bin/rails routes --unused report in Rails 8.1, and how far can you trust it before deleting routes?

level: seniorimportance: should knowfreq 26%

basics

~20 s

It lists routes whose controller class is missing, or whose action has neither a method nor a template, and exits 1 when it finds any. It ignores traffic and links, so a route that passes may still be dead.

open as a page

In config/routes.rb, why do Rails developers keep nesting to one level, and what does shallow: true change for episodes nested under shows?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Each nesting level adds a required id to every path and helper call, so Rails' guide advises one level. shallow: true keeps index, new and create under /shows/:show_id/episodes and moves show, edit, update and destroy to /episodes/:id.

open as a page

In a Rails app where photos are published and unpublished, why route to a separate resourceful controller instead of adding publish and unpublish actions to PhotosController?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Modelling publishing as a resource, resource :publication under each photo, maps publish to create and unpublish to destroy on a small controller, so every controller keeps to the seven actions and the routes stay predictable.

open as a page

In config/routes.rb, how do shallow_path and shallow_prefix change the shallow member routes of episodes, and why does a namespace set them?

level: middleimportance: nice to knowfreq 18%

basics

~20 s

shallow_path adds a path segment in front of shallow member URLs and shallow_prefix adds a prefix to their helper names; collection routes ignore both. A namespace sets both to its own name, so its shallow routes stay inside it.

open as a page

In a large Rails app's config/routes.rb, how do draw and mount help organise routing, and what does each one actually hand off?

level: seniorimportance: nice to knowfreq 18%

basics

~10 s

draw :admin evaluates config/routes/admin.rb in place, inside the current scope, so a big routes file can be split; mount hands every request under a path prefix, for any verb, to another Rack application.

open as a page

In config/routes.rb, what do direct and resolve define, and when would you reach for each one?

level: seniorimportance: nice to knowfreq 18%

basics

~10 s

direct :name defines a custom name_path / name_url helper whose block returns anything url_for accepts. resolve "Model" changes what polymorphic routing builds for that model, such as mapping a record to a singular resource.

open as a page