Вопрос

I have the following in my routes.rb file:

  resources :businesses do 
    resources :branches
  end

This (correctly) generates the following routes:

    business_branches GET    /businesses/:business_id/branches(.:format)          branches#index
                      POST   /businesses/:business_id/branches(.:format)          branches#create
  new_business_branch GET    /businesses/:business_id/branches/new(.:format)      branches#new
 edit_business_branch GET    /businesses/:business_id/branches/:id/edit(.:format) branches#edit
      business_branch GET    /businesses/:business_id/branches/:id(.:format)      branches#show
                      PUT    /businesses/:business_id/branches/:id(.:format)      branches#update
                      DELETE /businesses/:business_id/branches/:id(.:format)      branches#destroy

The problem is this: I'd like to enjoy the URL path nesting without having to change all my links to use the new path names.

I tried the following, to no avail:

  resources :businesses do 
    resources :branches, as 'branches'
  end
Это было полезно?

Решение

This isn't possible without changing your paths a little bit. For example you have to include the business_id.

So if you have:

resources :businesses do 
  resources :branches
end

the edit path for example should look like this:

edit_business_branch_path(business_id: 123, id: 456)

What you can do is to add a scope in your routes:

scope ":business_id" do
  resources :branches
end

Generated routes:

    branches GET    /:business_id/branches(.:format)           branches#index
             POST   /:business_id/branches(.:format)           branches#create
  new_branch GET    /:business_id/branches/new(.:format)       branches#new
 edit_branch GET    /:business_id/branches/:id/edit(.:format)  branches#edit
      branch GET    /:business_id/branches/:id(.:format)       branches#show
             PATCH  /:business_id/branches/:id(.:format)       branches#update
             PUT    /:business_id/branches/:id(.:format)       branches#update
             DELETE /:business_id/branches/:id(.:format)       branches#destroy

Now the path is like you want, but you still have to include the business_id:

edit_branch_path(business_id: 123, id: 456)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top