rails,为新路由添加参数

new操作通常不需要参数,因为它从头开始创建新资源。 在我的应用程序中,每当我创建某种类型的资源时,我都需要提供一个模板,这是另一book的ID。 所以我的new路线总是有一个参数。 我不知道如何将这个事实表示到routes.rb文件中。

因为我甚至不知道它是否可行,只是在它不是的情况下,那么我将创建一个new_wp,一个“new with parameter”动作。
我试着把它添加到我的

 resources :books, :only => [:edit, :update, :show, :new] do member do get 'new_wp/:template_id', :action => 'new_wp' end end 

但是rake路线说这不是我想要的:

 GET /books/:id/new_wp/:template_id(.:format) books#new_wp 

也就是说,它有两个参数。

尝试:

 resource ... get "new/:template_id", :to => "Books#new_wp", :on => :collection end # GET /books/new/:template_id(.:format) Books#new_wp 

我经常这样做,最简单的方法,我相信只是调整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 – 我的偏好和上面的牛排餐

 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来生成new_new_book 。 解决这个问题,你可以从get ":template_id" ...更改get ":template_id" ...get path: ":template_id"...这将生成new_book

如果你想要做的就是为new传递参数,我的偏好是场景3。 如果要更改操作,则需要考虑使用方案2但排除:new来自资源的:new或在您的情况下不添加:new to only:参数。