路由约束不能正确地为Rails参数分配值;使用“ +”分隔值 [英] Routing constraints don't assign values to a Rails parameter correctly; use '+' to delimit values
问题描述
我希望能够在我的应用程序的路线中支持国家或地区代码。例如:
I would like to be able to support country codes and region codes in my application's routes. For example:
- / entities / us
- / entities / us + ca
- / entities / us / mn
- / entities / us / mn / wi + ia
- / entities / us + ca / bc + wa
- /entities/us
- /entities/us+ca
- /entities/us/mn
- /entities/us/mn+wi+ia
- /entities/us+ca/bc+wa
我当前的路线:
get "/entities/:country_code/(:region_code)" => "entities#index", :constraints => {:country_code=>/[a-zA-Z]{2}[\+\,]?/, :region_code=>/[a-zA-Z]{2}[\+\,]?/}
resources :entities
尝试 / entities / us + ca
会导致以下异常:
# Use callbacks to share common setup or constraints between actions.
def set_entity
@entity = Entity.find(params[:id])
end
Application Trace | Framework Trace | Full Trace
app/controllers/entities_controller.rb:79:in `set_entity'
Request
Parameters:
{"id"=>"us+ca"}
我将路线更改为:
get "/entities/:country_code/(:region_code)" => "entities#index"
resources :entities
这允许多个国家和地区查询工作(即 us + ca
被分配给:country_code
参数),但这破坏了 / entities / new
路径- new
现在被认为是:country_code
参数。
This allows the multiple country and region query to work (i.e. us+ca
is assigned to the :country_code
parameter), but this broke the /entities/new
path--new
is now considered to be a :country_code
parameter.
我假设问题与正则表达式有关。
I'm assuming that the problem is related the the regular expressions.
是否存在正则表达式
推荐答案
我认为您的正则表达式不太正确。您在那里的那个将匹配2个字符,并可选地跟一个 +
或,
。您还需要允许后续的字符对。
I think your regex isn't quite right. The one you have there will match 2 characters optionally followed by a +
or a ,
. You need to also allow the subsequent character pairs.
尝试以下正则表达式: / [a-zA-Z] {2}(\ + [a-zA-Z] {2})* /
(匹配2个字符,后跟0个或多个 +
序列,后跟2个字符)。
Try this regex: /[a-zA-Z]{2}(\+[a-zA-Z]{2})*/
(that matches 2 characters followed by 0 or more sequences of +
followed by 2 characters).
这篇关于路由约束不能正确地为Rails参数分配值;使用“ +”分隔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!