Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 362
Asnad Atta Avatar asked Jun 05 '15 06:06

Asnad Atta


2 Answers

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.

like image 93
skplunkerin Avatar answered Nov 15 '22 23:11

skplunkerin


A more clean way is to use the member

resources :companies, param: :company_id do
  member do
    resources :shares, only[:index]
  end
end
like image 3
Jarl Avatar answered Nov 16 '22 00:11

Jarl