[英]Rails URL helpers turning wildcard path params into query params
We are using Rails 4.2.10. 我们正在使用Rails 4.2.10。 We have nested resource routes defined like
我们有如下定义的嵌套资源路由
resources :projects do
resources :items, except: [:show]
get '(:scope/(:scope2))/items/:id', to: 'items#show'
end
Now rake routes
yields as expected 现在
rake routes
产量达到预期
...
GET /projects/:project_id(/:scope(/:scope2))/items/:id(.:format) items#show
...
and calling the URL /projects/my-project/all/my/items/2.js
correctly sets the controller params to 并调用URL
/projects/my-project/all/my/items/2.js
正确地将控制器参数设置为
{
"controller"=>"items", "action"=>"show", "project_id"=>"my-project",
"id"=>"52328", "scope"=>"all", "scope2"=>"my"
}
We expect calling app.project_item_path('my-project', 2, scope: 'all', scope2: 'my', format: 'js')
on the console to yield 我们希望在
app.project_item_path('my-project', 2, scope: 'all', scope2: 'my', format: 'js')
调用app.project_item_path('my-project', 2, scope: 'all', scope2: 'my', format: 'js')
以产生
/projects/my-project/all/my/items/2.js
but it actually yields 但实际上产生了
/projects/my-project/items/2.js?scope=all&scope2=my
Why is that the case? 为什么会这样? How can we make rails fill in the wildcard params
:scope
and :scope2
in the positions given in the routes instead of making them query params? 我们如何使rails在路线中给定的位置填充通配符
:scope2
:scope
和:scope2
而不是使它们查询参数?
Similar to the proposal in the first answer, I tried 与第一个答案中的建议类似,我尝试了
resources :projects do
get '(:scope/(:scope2))/items/:id', to: 'items#show', as: :item
resources :items, except: [:show]
end
While this does not result in an immediate error, now calling app.project_item_path('my-project', 222, scope: 'all')
results in 虽然这不会立即导致错误,但是现在调用
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]
Could you try by adding "as" parameter to your route. 您可以尝试在路径中添加“ as”参数吗? For example;
例如;
resources :projects do
resources :items, except: [:show]
get '(:scope/(:scope2))/items/:id', to: 'items#show', as: :scoped_item
end
Then you can set your scope variables to this routes. 然后,您可以将范围变量设置为此路由。
app.project_scoped_item_path('my-project', 222, scope: 'all')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.