我经常这样做,我相信最简单的方法就是调整 path_names。这样你的路线名称就不会弄乱了。让我解释。
场景 1 - 标准导轨
代码
resources :books
输出
books GET /books(.:format) books#index
POST /books(.:format) books#create
new_book GET /books/new(.:format) books#new
edit_book GET /books/:id/edit(.:format) books#edit
book GET /books/:id(.:format) books#show
PATCH /books/:id(.:format) books#update
PUT /books/:id(.:format) books#update
DELETE /books/:id(.:format) books#destroy
场景 2 - Chris Heald 版本
代码
resources :books do
get "new/:template_id", to: "books#new_wp", on: :collection
end
# You can also do, same result with clearer intention
# resources :books do
# get ":template_id", to: "books#new_wp", on: :new
# end
输出
GET /books/new/:template_id(.:format) books#new_wp
books GET /books(.:format) books#index
POST /books(.:format) books#create
new_book GET /books/new(.:format) books#new
edit_book GET /books/:id/edit(.:format) books#edit
book GET /books/:id(.:format) books#show
PATCH /books/:id(.:format) books#update
PUT /books/:id(.:format) books#update
DELETE /books/:id(.:format) books#destroy
场景 3 - 我的首选和上面 steakchaser 指出的
代码
resources :books, path_names: {new: 'new/:template_id' }
输出
books GET /books(.:format) books#index
POST /books(.:format) books#create
new_book GET /books/new/:template_id(.:format) books#new
edit_book GET /books/:id/edit(.:format) books#edit
book GET /books/:id(.:format) books#show
PATCH /books/:id(.:format) books#update
PUT /books/:id(.:format) books#update
DELETE /books/:id(.:format) books#destroy
您会注意到,在场景 2 中您缺少路径名,这意味着您需要添加一个as: :new
which 会生成new_new_book
. 解决此问题,您可以将生成的更改get ":template_id" ...
为get path: ":template_id"...
new_book
如果您只想为 new 传递参数,我的首选是方案 3。如果您想更改操作,那么您需要考虑使用方案 2,但从:new
资源中排除,或者在您的情况下不要添加:new
到only:
参数中。