带有约束的Rails自定义路由 - 路由要求中不允许使用regexp锚点字符

ker*_*lin 13 regex routes syntax-error ruby-on-rails-3

我有以下路线:

  get 'users/:user_id/:name', to: 'profiles#show',
    :constraints => { :name => /[a-zA-Z0-9_]+$/ }, as: 'user_profile'
Run Code Online (Sandbox Code Playgroud)

哪会产生错误:

Regexp anchor characters are not allowed in routing requirements: /[a-zA-Z0-9_]+$/
Run Code Online (Sandbox Code Playgroud)

所以我得到^字符是不允许的,但不确定是什么字符产生这个特定的路由错误.

mah*_*off 15

正则表达式的锚是^$,但它们在这里没有任何成就."(Y)你不需要使用锚点,因为所有路线都在开始时锚定." .

所以约束:

:constraints => { :name => /[a-zA-Z0-9_]+/ }
Run Code Online (Sandbox Code Playgroud)

将做你想做的事 - 确保名称由这些字符中的一个或多个组成,而不是别的.顺便说一句,你可以简化正则表达式:

:constraints => { :name => /\w+/ }
Run Code Online (Sandbox Code Playgroud)

  • 在导轨2中使用。,:requirements => {:id => / [A-Z0-9] {1,}([\ / _-] {1} [A-Z0-9] {1,})* / i} (2认同)

Ωme*_*ega 14

在正则表达式中我们有两个锚点:

  1. 行/字符串的开头 ^
  2. 行尾/字符串 $

尝试$从模式中删除,你应该好好去......

  • 我知道的还有`\ A`和`\ Z`. (6认同)