问题
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
My current route:
get "/entities/:country_code/(:region_code)" => "entities#index", :constraints => {:country_code=>/[a-zA-Z]{2}[\+\,]?/, :region_code=>/[a-zA-Z]{2}[\+\,]?/}
resources :entities
Trying /entities/us+ca
results in this 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"}
I change the route to:
get "/entities/:country_code/(:region_code)" => "entities#index"
resources :entities
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.
Is there a regex that will work for my needs?
回答1:
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.
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).
回答2:
Do you think this would work
get '/entities/*country_code/*region_code', to: 'entities#index', constraints: { country_code: /[a-zA-Z]{2}[\+\,]?/, region_code: /[a-zA-Z]{2}[\+\,]?/ }
May need to play with your constraints regex.
来源:https://stackoverflow.com/questions/24456468/routing-constraints-dont-assign-values-to-a-rails-parameter-correctly-use