路由约束不会正确地为Rails参数赋值; 使用’+’分隔值
我希望能够在我的应用程序路由中支持国家/地区代码和区域代码。 例如:
- /实体/美
- /实体/我们+ CA
- /实体/ US /分钟
- /实体/ US / MN +无线+ IA
- /实体/我们+ 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
导致此exception:
# 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
参数。
我假设问题与正则表达式有关。
是否有适合我需求的正则表达式?
我认为你的正则表达不太正确。 你在那里的那个将匹配2个字符,可选地后跟一个+
或a ,
. 您还需要允许后续字符对。
试试这个正则表达式: /[a-zA-Z]{2}(\+[a-zA-Z]{2})*/
(匹配2个字符,后跟0或更多+
序列,后跟2个字符)。
你认为这会奏效吗?
get '/entities/*country_code/*region_code', to: 'entities#index', constraints: { country_code: /[a-zA-Z]{2}[\+\,]?/, region_code: /[a-zA-Z]{2}[\+\,]?/ }
可能需要使用你的约束正则表达式。