简体   繁体   中英

Rails URL helpers turning wildcard path params into query params

setup

We are using 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

working as expected

Now rake routes yields as expected

...

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

{
  "controller"=>"items", "action"=>"show", "project_id"=>"my-project",
  "id"=>"52328", "scope"=>"all", "scope2"=>"my"
}

not working as expected

We expect calling app.project_item_path('my-project', 2, scope: 'all', scope2: 'my', format: 'js') on the console to yield

/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?

update

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

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. 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM