0

我正在尝试创建一条允许:

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 

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

我错过了什么?

** 编辑 **

位置#index 操作:

# 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(与上述相同的错误)
4

1 回答 1

1

路线是从上到下搜索的,找到的第一条路线会被触发。因此,您get '/locations/:id' => 'locations#show'resources :locations组中的路线在您的约束之前优先。

所以路线的一般规则是你应该把更具体的路线放在比更常见的路线更高的位置。

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

于 2013-11-07T15:47:49.990 回答