In Rails, what is the difference between a named route's _path and _url helpers, and when do you need the _url form?
answer
- same route name, two suffixes
- relative path vs scheme plus host
- host comes from the current request
- links that leave the page
- extra keys become the query string
basics
~10 sBoth 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 sEvery 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# 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
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.
Explain where the _url host comes from during a request and why a job or rake task has no such source.
Decide per output channel: paths inside pages, absolute URLs for invites, emails, payloads and canonical links, with protocol and host configured per environment.
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