Rails路由约束被忽略

时间:2013-11-07 15:26:11

标签: ruby-on-rails ruby-on-rails-4

我正在尝试创建允许的路线:

GET /locations           # locations#index
...
GET /locations/:id       # locations#show
GET /locations/:regions  # get locations by one or more region codes (e.g. 'MN+WI')

我的路线:

resources :locations
# allow one or more, 2-character region codes (mixed case; comma or plus delimited)
get "/locations/:regions/" => "locations#index", :constraints => {:regions=>/[a-zA-Z]{2}[\+\,]?/}
root 'locations#index'

当我尝试连接到http://localhost:3000/locations/MN+WI时,出现错误,显示Couldn't find Location with id=MN+WI突出显示locations_controller的这一部分:

def set_location
  @location = Location.find(params[:id])
end 

由于某种原因,约束未匹配,导致无法通过数值识别资源的尝试。

我错过了什么?

**编辑**

locations #index action:

# GET /locations
# GET /locations.json
def index
  @locations = Location.order('name')
  @locations = Location.for_regions(params[:regions]) if params[:regions].present?
  @json = @locations.to_gmaps4rails
end

我重新安排了路线:

# allow one or more, 2-character region codes (mixed case; comma or plus delimited)
get "/locations/:regions/" => "locations#index", :constraints => {:regions=>/[a-zA-Z]{2}[\+\,]?/}
resources :locations
root 'locations#index'

成功:

  • http://localhost:3000/locations/1
  • http://localhost:3000/locations/MN

失败:

  • http://localhost:3000/locations/MN+WI(与上述相同的错误)

1 个答案:

答案 0 :(得分:1)

路线从上到下进行锯齿,找到的第一条路线被触发。因此,来自get '/locations/:id' => 'locations#show'组的resources :locations路由优先于您的约束。

因此,路线的一般规则是,您应该将更多特定路线设置为更常见的路线。

在这种情况下,您需要将该路线向上移动并将其放在资源之前。