3

I want to override the :id param and this explains how. But doesn't really work with nested resources. My routes look like:

resources :users, param: :user_id do
  resources :projects, param: :project_id
end

this generates url of format: :user_user_id/:project_id. I would rather have it as :user_id/:project_id. Can someone please help?

sonalkr132
  • 967
  • 1
  • 9
  • 25

2 Answers2

5

I know this is an old topic already answered, but as I see there is no explanation for why the code of @Зелёный works and not that of @sonalkr132 (I know this can seem off-topic, but @sonalkr132 posted another question which showed me that he didn't understand how it works)

When you create nested resources like projects inside users, rails you risk to have a path like users/:id/projects/:id, which is nonsense, so rails automatically adds a prefix to the first :id, and thus in params you have :user_id and :id (referencing to :project_id, but no doubt we are in the ProjectsController, so no further clarification is needed)

Now, when you say param: :user_id, this adds together with the prefix user_, that is why you get :user_user_id - you ask rails do the job twice.

Misu
  • 441
  • 5
  • 15
0

This code:

resources :users do
  resources :projects, param: :project_id
end

Generate routes like:

    user_projects GET    /users/:user_id/projects(.:format)                          projects#index
                  POST   /users/:user_id/projects(.:format)                          projects#create
 new_user_project GET    /users/:user_id/projects/new(.:format)                      projects#new
edit_user_project GET    /users/:user_id/projects/:project_id/edit(.:format)         projects#edit
     user_project GET    /users/:user_id/projects/:project_id(.:format)              projects#show
                  PATCH  /users/:user_id/projects/:project_id(.:format)              projects#update
                  PUT    /users/:user_id/projects/:project_id(.:format)              projects#update
                  DELETE /users/:user_id/projects/:project_id(.:format)              projects#destroy

Tested. Rails '4.2.1'

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
  • You did answer my question correctly but I needed more. My project resources has another nested resource `issues` in it. You can tell that your approach will not work in my usecase. I didn't add `issues` for the simplicity of the question. – sonalkr132 Aug 29 '15 at 09:15
  • @sonalkr132 make a new question and include a full case with a related code. – Roman Kiselenko Aug 29 '15 at 09:16
  • hey Зелёный! I have posted it here: http://stackoverflow.com/questions/32284593/overriding-params-in-nested-routes – sonalkr132 Aug 29 '15 at 09:33