Rails routes config认为action method是一个object id
Rails routes config thinks action method is an object id
我正在开发 rails 应用程序并遇到了这样的问题。
我有 movies_controller.rb
,其中定义了这些操作和路线:
Prefix Verb URI Pattern Controller#Action
movies GET /movies(.:format) movies#index
POST /movies(.:format) movies#create
new_movie GET /movies/new(.:format) movies#new
edit_movie GET /movies/:id/edit(.:format) movies#edit
movie GET /movies/:id(.:format) movies#show
PATCH /movies/:id(.:format) movies#update
PUT /movies/:id(.:format) movies#update
DELETE /movies/:id(.:format) movies#destroy
root GET / redirect(301, /movies)
movies_by_director GET /movies/by_director(.:format) movies#by_director
但是当我尝试转到 /movies/by_director?director="something"
时,rails 想,我正在使用参数 :id = by_director
.
导航到 movies#show
操作
我做错了什么?
路由按照指定的顺序匹配,因此请确保 "by_director" 的路由定义在 高于 电影资源路由的位置。
像这样应该可以解决问题:
get '/movies/by_director' => 'movies#by_director'
resources :movies
这里有两个问题:
:id
的默认模式匹配足够宽松,以至于 by_director
被解释为 :id
。
- 路由按顺序匹配,
GET /movies/:id
出现在GET
/movies/by_director
之前。
您可以在 resources :movie
之前手动将 GET /movies/by_director
定义为 ,或者您可以添加约束以缩小 :id
的范围:
resources :movies, constraints: { id: /\d+/ } do
#...
end
如果只有一两个路由需要处理,手动排序路由是可以的,约束 :id
是 (IMO) 更干净且更不容易出错。
我正在开发 rails 应用程序并遇到了这样的问题。
我有 movies_controller.rb
,其中定义了这些操作和路线:
Prefix Verb URI Pattern Controller#Action
movies GET /movies(.:format) movies#index
POST /movies(.:format) movies#create
new_movie GET /movies/new(.:format) movies#new
edit_movie GET /movies/:id/edit(.:format) movies#edit
movie GET /movies/:id(.:format) movies#show
PATCH /movies/:id(.:format) movies#update
PUT /movies/:id(.:format) movies#update
DELETE /movies/:id(.:format) movies#destroy
root GET / redirect(301, /movies)
movies_by_director GET /movies/by_director(.:format) movies#by_director
但是当我尝试转到 /movies/by_director?director="something"
时,rails 想,我正在使用参数 :id = by_director
.
movies#show
操作
我做错了什么?
路由按照指定的顺序匹配,因此请确保 "by_director" 的路由定义在 高于 电影资源路由的位置。
像这样应该可以解决问题:
get '/movies/by_director' => 'movies#by_director'
resources :movies
这里有两个问题:
:id
的默认模式匹配足够宽松,以至于by_director
被解释为:id
。- 路由按顺序匹配,
GET /movies/:id
出现在GET /movies/by_director
之前。
您可以在 resources :movie
之前手动将 GET /movies/by_director
定义为 :id
的范围:
resources :movies, constraints: { id: /\d+/ } do
#...
end
如果只有一两个路由需要处理,手动排序路由是可以的,约束 :id
是 (IMO) 更干净且更不容易出错。