i have in my application a custom route, that need to match everytime the param is a number or an list of numbers splited by |
在我的应用程序中有一个自定义路由,每次param是|分割的数字或数字列表时都需要匹配
this is my code:
这是我的代码:
get '/lists' => 'cidades#list'
get '/list(/:id)' => 'cidades#list', :constraints => { :id => /[0-9|]+/ }
get '/list(/:name)' => 'cidades#list'
what i hope to accomplish is something like this:
我希望完成的是这样的事情:
/lists => cidades#list
/list/1 => cidades#list & param[:id] = "1"
/list/1|2|3|4 => cidades#list & param[:id] = "1|2|3|4"
/list/1a => cidades#list & param[:name] = "1a"
if i use this regexp: /[0-9|]+/
i get 1a
to be valid, but i don't want this. I find this regexp: /\A[0-9|]+\Z/
but this gives me this error:
如果我使用这个regexp: /[0-9|]+/我得到1a是有效的,但是我不想要这个。我找到了这个regexp: /\A[0-9|]+\Z/但这给了我这个错误:
ArgumentError (Regexp anchor characters are not allowed in routing requirements: /\A[0-9|]+\Z/):
how can i create a constraint that will only match a numeric string? ( a string with only numbers )
如何创建只匹配数字字符串的约束?(只有数字的字符串)
2 个解决方案
#1
4
By default rails anchors the routing regular expressions so there is no need for the \A
and \Z
. I think you're looking for something that follows this pattern:
默认情况下,rails锚定路由正则表达式,因此不需要\A和\Z。我认为你是在寻找遵循这种模式的东西:
:constraints => { :id => /[0-9]+(\%7C[0-9]+)*/ }
This will force the route to have at least one integer (0-9). Optionally, the route can be followed by a | character (which is converted to %7C
by the browser). The | character is then followed by an additional integer (0-9). Putting this patter in its own group prevents having any lingering | after the integer ids.
这将迫使路由至少有一个整数(0-9)。可选地,路径后面可以跟着一个|字符(浏览器将其转换为%7C)。然后,|字符后面跟着一个额外的整数(0-9)。将此模式放入自己的组中可以防止在整数id之后有任何遗留|。
#2
0
You have to use something else than the spesial character | it's not allowed in urls.
你必须使用一些不允许在url中使用的特殊字符|。
I am not really sure what you are trying to do here. But, you could pass the :id's as an array of ids.
我不太确定你想在这里做什么。但是,您可以将:id作为id的数组传递。
ids = [1,2,3,4]
id =(1、2、3、4)
#1
4
By default rails anchors the routing regular expressions so there is no need for the \A
and \Z
. I think you're looking for something that follows this pattern:
默认情况下,rails锚定路由正则表达式,因此不需要\A和\Z。我认为你是在寻找遵循这种模式的东西:
:constraints => { :id => /[0-9]+(\%7C[0-9]+)*/ }
This will force the route to have at least one integer (0-9). Optionally, the route can be followed by a | character (which is converted to %7C
by the browser). The | character is then followed by an additional integer (0-9). Putting this patter in its own group prevents having any lingering | after the integer ids.
这将迫使路由至少有一个整数(0-9)。可选地,路径后面可以跟着一个|字符(浏览器将其转换为%7C)。然后,|字符后面跟着一个额外的整数(0-9)。将此模式放入自己的组中可以防止在整数id之后有任何遗留|。
#2
0
You have to use something else than the spesial character | it's not allowed in urls.
你必须使用一些不允许在url中使用的特殊字符|。
I am not really sure what you are trying to do here. But, you could pass the :id's as an array of ids.
我不太确定你想在这里做什么。但是,您可以将:id作为id的数组传递。
ids = [1,2,3,4]
id =(1、2、3、4)