问题
I have the following route:
get 'users/:user_id/:name', to: 'profiles#show',
:constraints => { :name => /[a-zA-Z0-9_]+$/ }, as: 'user_profile'
Which produces the error:
Regexp anchor characters are not allowed in routing requirements: /[a-zA-Z0-9_]+$/
So I get that the ^ character isn't allowed, but not sure what character is producing this particular routing error.
回答1:
In regex we have two anchors:
- Beginning of line/string
^
- End of line/string
$
Try to remove $
from the pattern and you should be good to go...
回答2:
The regex anchors are ^
and $
, but they don't achieve anything here. "(Y)ou don’t need to use anchors because all routes are anchored at the start.".
So the constraint:
:constraints => { :name => /[a-zA-Z0-9_]+/ }
will do what you want - ensure the name is composed of 1 or more of those characters, and nothing else. BTW you can simplify the regex:
:constraints => { :name => /\w+/ }
来源:https://stackoverflow.com/questions/13222382/rails-custom-route-with-constraints-regexp-anchor-characters-are-not-allowed-i