嵌套资源时是否可以保留旧路径?

时间:2014-05-12 18:25:10

标签: ruby-on-rails routes

我的routes.rb文件中包含以下内容:

  resources :businesses do 
    resources :branches
  end

这(正确)生成以下路线:

    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

问题是:我想享受网址路径嵌套而无需更改所有链接以使用新路径名称。

我尝试了以下内容,但无济于事:

  resources :businesses do 
    resources :branches, as 'branches'
  end

1 个答案:

答案 0 :(得分:0)

在不改变路径的情况下,这是不可能的。例如,您必须包含business_id。

所以如果你有:

resources :businesses do 
  resources :branches
end

例如,编辑路径应如下所示:

edit_business_branch_path(business_id: 123, id: 456)

您可以做的是在路线中添加范围:

scope ":business_id" do
  resources :branches
end

生成的路线:

    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

现在路径就像你想要的那样,你仍然需要包含business_id:

edit_branch_path(business_id: 123, id: 456)