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:
参数。
- 使用qunit测试emberjs / rails / devise应用程序时“无法validationCSRF令牌真实性”
- undefined局部变量或方法`start_test_server_in_background’for main:Object
- 无法在ruby 2.3.1上安装rails gem
- 重新加载rails控制台
- Errno :: EACCES:运行rake test:models时,权限被拒绝@ unlink_internal
- Redmine中的用户名
- OmniAuth before_filter要求登录
- “rake db:seed”和rake db:fixtures:load“之间的区别是什么?
- rails 3 + devise:如何修改邮件方法以确认电子邮件添加用户的第二个电子邮件地址
- rails 3:使用devise进行身份validation,如何允许使用guid而不是登录来访问报告页面
- CarrierWave并resize到特定宽度