In Rails, how do polymorphic_path and url_for build a URL from a record, a class or an array like [@studio, @session]?
answer
- model_name route keys
- persisted? picks member or collection
- symbols add namespaces to the array
- nil parents are compacted away
- the helper must actually exist
basics
~20 spolymorphic_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).
solid answer
~40 sPolymorphic routing reads `model_name` from each object. A persisted record uses `singular_route_key` and is passed as an argument, so `polymorphic_path(@session)` calls `class_session_path(@session)`; a new record or a class uses the plural `route_key`, giving `class_sessions_path`. An array is joined into one nested name: `[@studio, @session]` becomes `studio_class_session_path(@studio, @session)`, and symbols add prefixes or suffixes, so `[:admin, @studio]` becomes `admin_studio_path(@studio)`. `edit_polymorphic_path` and `new_polymorphic_path`, or `action:`, add the prefix. `url_for` delegates here when given a record or array: a controller's `url_for` returns the full URL, while a view's returns a path. If the computed helper does not exist you get `NoMethodError`, and nil elements in the array are dropped silently.
code
ruby · 13 lines# config/routes.rb
resources :studios do
resources :class_sessions, only: [:index, :show, :new, :create]
end
namespace :admin do
resources :studios
end
# in a controller action
polymorphic_path([@studio, @session]) # => "/studios/3/class_sessions/42"
polymorphic_path([@studio, ClassSession.new]) # => "/studios/3/class_sessions"
polymorphic_path([:admin, @studio]) # => "/admin/studios/3"
url_for([@studio, @session]) # => "https://studio.example/studios/3/class_sessions/42"go deeper
Recall that redirect_to @record and link_to with a record use polymorphic routing to pick the record's helper.
Explain the naming rules: singular for persisted records, plural for new records and classes, arrays for nesting and symbols for namespaces.
Spot the silent nil-compaction and STI naming traps, and choose explicit helpers outside genuinely generic code.
Keep route naming and model naming aligned across the app so generic code stays predictable, and document where polymorphic URLs are allowed.
## What polymorphic routing is Named-route helpers such as `studio_class_session_path` force you to know the record's type and nesting. **Polymorphic routing** works it out from the objects themselves. It powers `polymorphic_path` / `polymorphic_url`, `url_for` with a record, and everything built on them: `redirect_to @session`, `link_to` with a record, and `form_with(model: ...)` in views. The rule is mechanical: Rails builds a **helper name** from the objects, then calls that helper with the records as arguments. ## The naming rules Each object contributes a piece of the name, read from its `model_name`: | Object | Piece of the name | Passed as argument? | |---|---|---| | Persisted record (`@session`) | `singular_route_key` → `class_session` | yes | | New record (`ClassSession.new`) as the last element | plural `route_key` → `class_sessions` | no | | Class (`ClassSession`) as the last element | plural `route_key` → `class_sessions` | no | | Symbol (`:admin`) | the symbol itself | no | | Parent record before the last element | `singular_route_key` | yes | Rails joins the pieces with underscores and appends `_path` or `_url`: ```ruby polymorphic_path(@session) # class_session_path(@session) polymorphic_path(ClassSession.new) # class_sessions_path polymorphic_path([@studio, @session]) # studio_class_session_path(@studio, @session) polymorphic_path([@studio, ClassSession.new]) # studio_class_sessions_path(@studio) polymorphic_path([:admin, @studio]) # admin_studio_path(@studio) edit_polymorphic_path([@studio, @session]) # edit_studio_class_session_path(...) ``` The prefixed helpers `edit_polymorphic_path` / `new_polymorphic_path` are shorthand for `action: :edit` / `action: :new`. `polymorphic_url` takes `routing_type: :path` if you ever need to flip it, and accepts the usual options such as `anchor:` and `format:`. ## url_for in controllers and views `url_for` accepts a string, a hash, a record, a class or an array. For a record or array it delegates to polymorphic routing, but the default differs by context: - In a **controller**, `url_for(@session)` returns the full URL (`polymorphic_url`). - In a **view**, `url_for(@session)` returns a path, because views generate paths by default; pass `host:` or call `polymorphic_url` for an absolute link. - With a **hash**, `url_for(controller: "class_sessions", action: "show", id: 42)` matches routes by controller and action, filling missing keys from the current request's path parameters. ## The traps 1. **The helper must exist.** Polymorphic routing only computes a name. If the routes do not define it, the call raises `NoMethodError` for, say, `studio_class_session_path`. Nested arrays require nested routes. 2. **nil parents vanish.** Arrays are compacted before the name is built, so `[@studio, @session]` with `@studio` nil quietly becomes `class_session_path(@session)`. That either hits an unintended top-level route or raises `NoMethodError`, far from the real bug. A bare `nil` (or an all-nil array) raises `ArgumentError` with "Nil location provided. Can't build URI." 3. **Strings are refused.** Use symbols for namespace pieces; a String inside the array raises `ArgumentError` ("Please use symbols for polymorphic route arguments."). 4. **Single-table inheritance.** A subclass has its own `model_name`, so a `HotYogaSession < ClassSession` looks for `hot_yoga_session_path` unless you add routes for it, override its naming or map it with `resolve`. 5. **Uncountable names.** When singular and plural are equal, the collection key gets an `_index` suffix (`equipment_index_path`), which surprises people reading the helper names. ## Debugging a wrong or missing helper When a polymorphic call fails, compare the name Rails computed with the names the routes define: ```ruby ClassSession.model_name.singular_route_key # => "class_session" ClassSession.model_name.route_key # => "class_sessions" ``` The `NoMethodError` message carries the computed name, such as `studio_class_session_path`; the Prefix column of the route table shows what exists. A namespaced model such as `Studio::Room` contributes `studio_room`, which surprises people who routed it as plain `rooms`. Most fixes are one of three: add the nested route, pass the right array (a missing parent, an extra symbol), or map the model explicitly with `resolve`. ## When to prefer explicit helpers Polymorphic calls shine in shared partials and generic code that handles several models. In ordinary controllers and views, an explicit helper such as `studio_class_session_path(@studio, @session)` is easier to grep and fails at the call site with a clearer error. Most teams use both: explicit helpers by default, polymorphic routing where the type really varies.
- In Rails, what does polymorphic_path([@studio, @session]) do when @studio is nil?The array is compacted first, so the nil disappears and Rails calls `class_session_path(@session)`. If a top-level route exists, you get a link to the wrong place; if not, `NoMethodError`. Only a bare nil or an array with nothing left raises `ArgumentError` ("Nil location provided"). Check for the parent explicitly where it can be missing.
- Why does polymorphic_path(@session) fail for a HotYogaSession < ClassSession record in Rails?An STI subclass gets its own `model_name`, so polymorphic routing computes `hot_yoga_session_path`, which the routes never defined, and the call raises `NoMethodError`. Fix it with a route for the subclass, by making the subclass report the parent's naming, or with a `resolve "HotYogaSession"` mapping that returns the parent's route.
- polymorphic_path checks that the route exists before building the name
- A nil parent in the array raises an error immediately
- url_for(@session) returns a full URL in views as well as controllers
- A new record maps to the show route with an empty id
- Namespace pieces can be passed as Strings like "admin"