Home Rails URL helpers turning wildcard path params into query params
Reply: 0

Rails URL helpers turning wildcard path params into query params

user1951
1#
user1951 Published in July 20, 2018, 1:12 am

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]
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.30987 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO