skip to content

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

level: seniorimportance: nice to knowfreq 18%

answer

  1. custom _path and _url pair
  2. block returns string, hash, array or record
  3. resolve rewrites polymorphic URLs
  4. singular resource and form_with
  5. not allowed inside scope blocks

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.

solid answer

~40 s

`direct :pass_checkout do |pass| ... end` defines `pass_checkout_path` and `pass_checkout_url`. The block may return a string, a hash for `url_for`, an array for polymorphic routing, a record or a class, and the helper passes that through `url_for`. It is handy for external URLs or computed links you want named in one place. `resolve "Membership" { [:membership] }` instead changes **polymorphic** routing for that model: `link_to @membership`, `redirect_to @membership` and `form_with(model: @membership)` then point at the singular `/membership` route rather than `/memberships/:id`. It applies only when a single record is passed, not an array. Both must sit at the top level of the routes file; inside `scope` or `namespace` they raise. Neither adds a route, so neither shows up in the route table.

code

ruby · 16 lines
ruby
# config/routes.rb
Rails.application.routes.draw do
  resource :membership
  resources :studios do
    resources :class_sessions
  end

  resolve("Membership") { [:membership] }

  direct :class_booking do |session, options|
    [session.studio, session, options.merge(anchor: "booking")]
  end
end

# class_booking_url(session) => "https://studio.example/studios/3/class_sessions/42#booking"
# form_with(model: @membership) posts to /membership

go deeper

for a junior

Recall that direct defines a custom helper pair and resolve changes where a model's records link.

for a middle

Explain what the direct block may return and why resolve is the fix for singular resources with form_with.

for a senior

Use direct for named external links and resolve for polymorphic special cases, minding the top-level rule, caller context and _path stripping.

for a principal

Keep custom URL logic rare and centralized so generic code stays predictable and URL changes happen in one file.

## Two hooks into URL generation Most URL helpers come from routes. `direct` and `resolve` are routing-DSL methods that change **URL generation without adding routes**: - `direct` defines a **new named helper pair** whose output you compute; - `resolve` changes what **polymorphic routing** produces for a model class. Because neither creates a route, neither appears in `bin/rails routes`; they live in the routes file only so that every helper is defined in one place. ## direct: a named helper with custom logic ```ruby # config/routes.rb direct :studio_map do |studio| "https://maps.example.com/?q=#{CGI.escape(studio.address)}" end direct :class_booking do |session, options| [session.studio, session, options.merge(anchor: "booking")] end ``` The block's return value is passed to `url_for`, so it may be: - a **string**, treated as the finished URL (good for external links); - a **hash** of `url_for` options such as `{ controller: "pages", action: "index", subdomain: "www" }`; - an **array**, passed to polymorphic routing; - an **Active Model record or class**. Details that bite: 1. **The _path form strips the origin.** `class_booking_path(session)` returns the path part of the computed URL. For a string target such as the map link, `studio_map_path` drops the scheme and host, so use `studio_map_url` for external targets. 2. **Default options.** `direct :browse, page: 1 do |options| ... end` passes defaults to the block, merged with what the caller passes. 3. **Context.** The block runs in the caller's context. Code that uses `params` works in a controller or view but raises `NameError` from `Rails.application.routes.url_helpers`. 4. **No recursion.** Calling the same helper inside its own block overflows the stack; use `route_for(:other_name, ...)` to call another named or custom helper and keep the caller's path-or-URL choice. ## resolve: changing polymorphic routing for one model A studio member has exactly one membership, routed as a **singular resource**: ```ruby resource :membership resolve("Membership") { [:membership] } ``` Without `resolve`, polymorphic routing would compute `membership_path(@membership)`. The singular route has no `:id`, so the positional record lands in the optional format slot and the link comes out as something like `/membership.7`. With it, every polymorphic call for a `Membership` record (`link_to "Membership", @membership`, `redirect_to @membership`, `form_with(model: @membership)`) generates `/membership`. The block receives the record (and, with two parameters, the options) and returns anything polymorphic routing accepts. Its reach is deliberately narrow: - it applies when **a single record** is passed; - an array such as `[:admin, @membership]` ignores the mapping and uses the normal rules; - the mapping is keyed by the model's class name, so an STI subclass needs its own `resolve` line. ## Choosing between them | Need | Tool | |---|---| | A named helper for an external or computed URL | `direct` | | One place to change a link used across many views | `direct` | | `form_with(model: record)` should hit a singular resource | `resolve` | | Records of a model should link somewhere other than their default route | `resolve` | | A new path that the app must answer | a real route, not either of these | ## Chaining helpers with route_for A custom helper often wants to delegate to another helper while keeping the caller’s choice of path or URL. `route_for` does that: ```ruby direct :session_venue do |session| route_for(:studio, session.studio) end session_venue_path(session) # => "/studios/3" session_venue_url(session) # => "https://studio.example/studios/3" ``` The block names the target once, and both generated helpers stay consistent. Calling `session_venue_url` from inside its own block instead would recurse until the stack overflows, which is why the API documentation warns against it. ## Restrictions - Both must be called at the **top level** of the routes block. Inside `scope`, `namespace` or `constraints` they raise `RuntimeError` ("The direct method can't be used inside a routes scope block"). - They are evaluated when the routes load, but the blocks run at URL-generation time, so slow work inside them (a database lookup per link) is paid on every call. Used sparingly, they keep special-case URL logic named, discoverable and out of views.

  • Why does a direct helper in config/routes.rb that reads params fail inside a Rails job?
    The block runs in the caller's context. In a controller or view, `params` is a method there; through `Rails.application.routes.url_helpers` in a job there is no `params`, so the block raises `NameError`. Pass what the block needs as arguments or options instead of reading request state.
  • Does resolve("Membership") { [:membership] } change link_to [:admin, @membership] in Rails?
    No. A polymorphic mapping applies only when a single record is passed. With an array, Rails builds the name from the array as usual, so `[:admin, @membership]` still looks for the admin membership helper. Add explicit routes or helpers for those cases.

  • direct adds a route that bin/rails routes lists
  • resolve also rewrites arrays like [:admin, @membership]
  • direct and resolve can be nested inside a namespace block
  • A direct helper's _path form keeps the scheme and host of a string target
  • The direct block is evaluated once at boot and cached