我们正在使用Rails 4.2.10。 我们有嵌套的资源路由,如
resources :projects do
resources :items, except: [:show]
get '(:scope/(:scope2))/items/:id', to: 'items#show'
end
现在rake routes
按预期产出
...
GET /projects/:project_id(/:scope(/:scope2))/items/:id(.:format) items#show
...
并调用URL /projects/my-project/all/my/items/2.js
正确地将控制器参数设置为
{
"controller"=>"items", "action"=>"show", "project_id"=>"my-project",
"id"=>"52328", "scope"=>"all", "scope2"=>"my"
}
我们希望在控制台上调用app.project_item_path('my-project', 2, scope: 'all', scope2: 'my', format: 'js')
以产生
/projects/my-project/all/my/items/2.js
但它确实产生了
/projects/my-project/items/2.js?scope=all&scope2=my
为什么会这样?我们如何在路由中给出的位置中使用通配符:scope
和:scope2
来填充轨道而不是使它们查询参数?
与第一个答案中的提案类似,我尝试了
resources :projects do
get '(:scope/(:scope2))/items/:id', to: 'items#show', as: :item
resources :items, except: [:show]
end
虽然这不会立即导致错误,但现在调用app.project_item_path('my-project', 222, scope: 'all')
会导致
ActionController::UrlGenerationError: No route matches
{:action=>"show", :project_id=>"my-project", :controller=>"items",
:id=>nil, :scope=>"all", :scope2=>222} missing required keys: [:id]
答案 0 :(得分:1)
你能尝试添加" as"路线参数。例如;
resources :projects do
resources :items, except: [:show]
get '(:scope/(:scope2))/items/:id', to: 'items#show', as: :scoped_item
end
然后您可以将范围变量设置为此路线。
app.project_scoped_item_path('my-project', 222, scope: 'all')