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?
answer
- first matching route wins
- :id happily matches nearby
- the 404 is RecordNotFound, not routing
- routes -g with the real URL
- recognize_path shows the winner
basics
~10 sRails 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.
solid answer
~40 sThe router walks the table in the order `config/routes.rb` declares it and dispatches to the first route whose verb, pattern and constraints fit. `resources :bikes` comes first and includes `GET /bikes/:id(.:format)`; a dynamic segment matches any text without a slash or dot, so `nearby` becomes `params[:id]`. `BikesController#show` runs `Bike.find("nearby")`, which raises `ActiveRecord::RecordNotFound`, and production renders a 404. So this is a shadowed route, not a missing one. Confirm it with `bin/rails routes -g /bikes/nearby`, where the first GET row is the winner, or with `Rails.application.routes.recognize_path("/bikes/nearby")`, which returns `{controller: "bikes", action: "show", id: "nearby"}`. Fix it by declaring `nearby` before `resources :bikes`, by moving it into a `collection` block, or by constraining `:id` to digits.
code
ruby · 12 lines# config/routes.rb (bug)
resources :bikes
get "bikes/nearby", to: "bikes#nearby" # shadowed by bikes#show
# console
Rails.application.routes.recognize_path("/bikes/nearby")
# => {controller: "bikes", action: "show", id: "nearby"}
# config/routes.rb (fix)
resources :bikes do
collection { get :nearby }
endgo deeper
Recall that routes are matched top to bottom and that resources :bikes includes a GET /bikes/:id route.
Explain why :id matches nearby, why the 404 comes from RecordNotFound, and how a collection route fixes it.
Diagnose shadowing quickly with routes -g on the real URL, recognize_path and the log line, then prevent it with constraints and routing tests.
Set routes-file conventions, such as resource blocks for extra actions and globs last, so ordering bugs stop recurring as the app grows.
## The symptom The bike-share app adds a page listing bikes near the rider: ```ruby # config/routes.rb resources :bikes get "bikes/nearby", to: "bikes#nearby" ``` In development the page fails with `ActiveRecord::RecordNotFound` (`Couldn't find Bike with 'id'="nearby"`); in production it is a plain 404. The `nearby` action never runs, and the log says `Processing by BikesController#show` with `Parameters: {"id" => "nearby"}`. ## Why: first match wins The Rails router does not pick the most specific route. It keeps the routes in **declaration order** and, for each request: 1. narrows the table to routes whose path pattern fits the URL; 2. drops those whose verb or request-based constraints (such as `subdomain:`) do not fit; 3. tries the rest **in order** and dispatches to the first one that accepts the request. `resources :bikes` expands to seven routes, including `GET /bikes/:id(.:format)` for `show`. A dynamic segment like `:id` matches any run of characters except a slash, a dot or a question mark, so the word `nearby` is a perfectly good `:id`. The `show` route is earlier in the file, so it wins, and the later `bikes/nearby` line is **shadowed**: it exists in the table but can never be reached by a GET. Note what the 404 really is. Routing **succeeded**; the action ran and the record lookup failed. A route that was truly missing would end as a routing error instead, which is why reading the log line matters. ## Confirming the diagnosis | Tool | What it shows | |---|---| | `bin/rails routes -g /bikes/nearby` | Every route whose pattern matches the URL, in priority order; the first GET row wins | | `Rails.application.routes.recognize_path("/bikes/nearby")` | The params of the winning controller route: `{controller: "bikes", action: "show", id: "nearby"}` | | `/rails/info/routes` in development | The same ordered table with a path search box | | The request log | `Processing by BikesController#show` and the `id` param | `recognize_path` takes `method:` for other verbs, such as `recognize_path("/bikes/nearby", method: :delete)`, and raises `ActionController::RoutingError` ("No route matches") when nothing fits. ## Fixing it Three fixes, from most to least idiomatic: - **Make it a collection route**, so `resources` declares it before `show`: ```ruby resources :bikes do collection { get :nearby } end ``` - **Move the line above** `resources :bikes`. It works, but the next person may move it back. - **Constrain the id** with `constraints: { id: /\d+/ }` on the resource, so `nearby` fails the `show` pattern and the router moves on. This also protects other words later added under `/bikes/`. After the fix, `bin/rails routes -g /bikes/nearby` should list `nearby_bikes GET /bikes/nearby(.:format) bikes#nearby` above the show row. ## Verbs and constraints decide who competes Only routes that fit the request take part in the ordering: - **The verb filters first.** `PATCH /bikes/nearby` lands in `bikes#update` with `id: "nearby"`, while a `POST` matches no `:id` route at all and ends as a routing error. - **HEAD borrows GET routes.** A `HEAD /bikes/nearby` with no explicit HEAD route is matched against the GET routes, so it is shadowed the same way. - **Request constraints filter too.** A route limited to `subdomain: "admin"` never competes on other hosts. - **Object and lambda constraints pass.** When one returns false, the router continues to the next candidate, so a constrained route above another one does not block it. The ordering rule is therefore "first route that accepts this verb, path and request", not "first line that mentions the path". ## Where the same mistake hides - **Catch-all globs** (`get "*path"`) placed anywhere but last swallow everything below them. - **Generic patterns** like `get ":slug", to: "pages#show"` at the top shadow later top-level routes. - **Routes added by gems or frameworks** load after your file, so your own broad patterns can shadow them. - **Split route files** (`draw(:admin)`) insert their routes where the `draw` line sits, so the position of that line sets their priority. ## Preventing it - Prefer `member` and `collection` blocks for extra actions on a resource. - Constrain ids where the format is known. - Pin important URLs with routing assertions, such as `assert_recognizes({controller: "bikes", action: "nearby"}, "/bikes/nearby")`, so a reordering breaks a test instead of production.
- Why can Rails.application.routes.recognize_path disagree with what a real request does?It only reports routes that dispatch to a controller (or into an engine). A `redirect(...)` route or a mounted Rack app earlier in the table is skipped, so `recognize_path` may name a later controller route while the live request is answered by the redirect. It also evaluates request constraints against a mock request on example.org unless you pass a full URL, so subdomain routes need `recognize_path("http://admin.example.com/...")`.
- In Rails, why is the shadowed /bikes/nearby a 404 rather than a routing error?Routing succeeded: `show` matched and ran. The failure came from `Bike.find("nearby")`, which raises `ActiveRecord::RecordNotFound`, and production maps that exception to a 404 page. A path that matches no route at all raises `ActionController::RoutingError` instead. The log line, `Processing by BikesController#show`, tells the two apart.
The router is a receptionist who reads the visitor list from the top and sends the guest to the first name that fits; a generic 'any visitor for bikes' line above 'nearby bikes' sends everyone to the wrong desk.
- Rails picks the most specific route, so static paths beat :id
- A 404 here means the nearby route is missing from the table
- Routes defined later override earlier ones with the same path
- recognize_path dispatches the request and runs the action
- The order of lines in config/routes.rb only affects bin/rails routes output