问题
Assume a Rails application draws the following routes (i.e. this is what rake routes
would show):
Verb URI Pattern Controller#Action
GET / one#show
GET / two#show
GET / three#show
What is the matching order for these routes when requesting the root path (i.e. /
)? What factors detemine which route is matched first?
Background: I’m faced with a Rails application (Discourse) for which I’m writing a plugin. The Rails application sets up a bunch of root routes via root to:
in its routes.rb file. My plugin tries to supply its own root route like this:
Discourse::Application.routes.append do
root to: 'custom#show'
end
… adding a new route to the output from rake routes
:
Verb URI Pattern Controller#Action
GET / one#show
GET / two#show
GET / three#show
GET / customshow
My problem is that I am not unable to make this new root take precedence over the other root routes. I tried using prepend
instead of append
which moves the custom root route to the top of the output, but it is still not matched first.
Edit: Presumably, routes are matched in the order they’re specified in, no matter the order from the rake routes
output.
回答1:
The first matched route will be the one specified earlier in routes.rb
.
Rails routes are matched in the order they are specified, so if you have a
resources :photos
above a get'photos/poll'
the show action's route for the resources line will be matched before the get line. To fix this, move the get line above the resources line so that it is matched first.
Source: link, second note
来源:https://stackoverflow.com/questions/55278994/for-routes-with-identical-uri-patterns-which-is-matched-first