Change the name of parent :parent_id parameter in Routing resources for Rails4

2.4k views Asked by At

I can change the name of the :id parameter in routing with in this way but this can change the nested resource's parameter like if I have

resources :companies, param: :company_id do
  resources :shares, only[:index]
end

this will generate route like

/companies/:company_company_id/shares

which is wrong I want route like this

/companies/:company_id/shares

What I need to do?

2

There are 2 answers

0
skplunkerin On BEST ANSWER

I've experienced this before and got the below to fix this... it's ugly though, but I haven't found a better way.

Change:

resources :companies, param: :company_id do
  resources :shares, only: [:index]
end

To: (notice the blank only: [])

resources :companies, param: :company_id
resources :companies, only: [], param: :id do
  resources :shares, only: [:index]
end

Now when you run rake routes you'll see the correct:

/companies/:company_id/shares(.:format)

in addition to all the other companies endpoints:

/companies(.:format)
/companies(.:format)
/companies/new(.:format)
/companies/:company_id/edit(.:format)
/companies/:company_id(.:format)
/companies/:company_id(.:format)
/companies/:company_id(.:format)
/companies/:company_id(.:format)

All keeping the same :company_id param name.

0
Jarl On

A more clean way is to use the member

resources :companies, param: :company_id do
  member do
    resources :shares, only[:index]
  end
end