Rails custom route with constraints - regexp anchor characters are not allowed in routing requirements

╄→гoц情女王★ 提交于 2021-02-07 11:29:11

问题


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:

  1. Beginning of line/string ^
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!