Rails URL助手将通配符路径参数转换为查询参数

时间:2018-04-10 11:24:28

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

设置

我们正在使用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]

1 个答案:

答案 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')