如何在config / routes.rb中的'do'关键字中添加DELETE方法?

时间:2017-07-04 04:25:04

标签: ruby-on-rails

我知道我可以通过编辑config / routes.rb在http://localhost:3000/students上添加一个新的DELETE方法:

resources :students
delete '/students',:to => 'students#destroymany'

注意:它与DELETE http://localhost:3000/students/1不同,因为默认的DELETE仅支持删除1个学生,而我还想支持http://localhost:3000/students/上的DELETE(没有特定的学生ID)

但它有一个缺点:我需要重复输入'学生'。是否有任何语法将路由语句更改为

resources :students do
    xxx
end

但与初始版本具有相同的效果?我试过了:

resources :students do
  delete '',:to => 'students#destroymany'
end

但错误发生了:

No route matches [DELETE] "/students"

因为它将路由添加到

/students/:student_id

而不是

/students

3 个答案:

答案 0 :(得分:1)

  

它与DELETE http://localhost:3000/students/1不同,因为   默认的DELETE仅支持删除1个学生,而我也想要   支持http://localhost:3000/students/上的DELETE(没有具体说明   学生ID)

将其添加到collection然后

resources :students do
  delete '', :to => 'students#destroymany', on: :collection
end

这将给出以下路线

DELETE /students(.:format)  students#destroymany

因此,您可以使用/students

致电method: :delete

答案 1 :(得分:0)

你可以这样做,因为你想要完成的目标:

resource :students do 
  collection do 
    delete '', to: 'students#destroymany'
  end
end

答案 2 :(得分:0)

利用单一资源。奇异资源将为您提供没有任何ID的删除路径

resource :students

DELETE /学生#destroy 请参阅singular resource

相关问题