我希望在路由的命名约定方面保持一致。任何资源的默认参数都是:id
。但是,如果在其中嵌套另一个资源,父资源的参数将更改为:parent_id
。
我的路由如下:
resources :users do
resources :projects do
resources :issues
end
end
对于用户模型,它会生成类似:id
的网址,对于项目网址将为:user_id/:id
,对于问题,网址将为:user_id/:project_id/:id
。我试图在this
resources :users, param: :user_id do
resources :projects, param: :project_id do
resources :issues, param: :issue_id
end
end
它生成的网址如下::user_user_id/:project_project_id/:issue_id
。由于我重写它,我希望父资源的默认附加是关闭的。我希望我的路线看起来像:user_id/:project_id/:issue_id
,我希望它对所有模型都保持一致。即项目应映射到:user_id/:project_id
。
答案 0 :(得分:9)
这就是我这样做的方式......不确定是否有更好的方法,但应该做到这一点......
resources :users, param: :user_id
resources :users, only: [] do
resources :projects, param: :project_id
end
resources :users, only: [] do
resources :projects, only: [] do
resources :issues, param: :issue_id
end
end
答案 1 :(得分:4)
尝试member
:
resources :users, param: :user_id do
member do
resources :projects, param: :project_id do
member do
resources :issues, param: :issue_id
end
end
end
end
此代码将生成以下路径:
issues GET /users/:user_id/projects/:project_id/issues(.:format) issues#index
POST /users/:user_id/projects/:project_id/issues(.:format) issues#create
new_issue GET /users/:user_id/projects/:project_id/issues/new(.:format) issues#new
edit_issue GET /users/:user_id/projects/:project_id/issues/:issue_id/edit(.:format) issues#edit
issue GET /users/:user_id/projects/:project_id/issues/:issue_id(.:format) issues#show
PATCH /users/:user_id/projects/:project_id/issues/:issue_id(.:format) issues#update
PUT /users/:user_id/projects/:project_id/issues/:issue_id(.:format) issues#update
DELETE /users/:user_id/projects/:project_id/issues/:issue_id(.:format) issues#destroy
projects GET /users/:user_id/projects(.:format) projects#index
POST /users/:user_id/projects(.:format) projects#create
new_project GET /users/:user_id/projects/new(.:format) projects#new
edit_project GET /users/:user_id/projects/:project_id/edit(.:format) projects#edit
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
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:user_id/edit(.:format) users#edit
user GET /users/:user_id(.:format) users#show
PATCH /users/:user_id(.:format) users#update
PUT /users/:user_id(.:format) users#update
DELETE /users/:user_id(.:format) users#destroy
然而,注意,帮助者与接受的答案不同。
您可以使用'作为'避免这种情况的选择。这里有更灵活的解决方案:https://stackoverflow.com/a/41323489/2405850
答案 2 :(得分:0)
在routes.rb
中尝试这些路线 resources :users, :key => :user_id do
resources :projects, :key => :project_id do
resources :issues, :key => :issue_id
end
end