ruby-on-rails – 删除后的Rails重定向使用DELETE而不是GET

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 删除后的Rails重定向使用DELETE而不是GET前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个路由,我正在发出一个DELETE:
user_authorization_path(@user,authorization)

它触发我的控制器,控制器删除资源,然后发出重定向

redirect_to edit_user_path(params[:user_id])

这样做的结果是重定向上的路由错误

ActionController::RoutingError (No route matches [DELETE] "/users/1/edit")

我可以在日志中看到rails正在做正确的事情,直到重定向,它试图发出另一个DELETE而不是GET:

Started DELETE "/users/1/authorizations/12"...
...
Redirected to http://localhost:3000/users/1/edit
Completed 302 Found in 8ms (ActiveRecord: 0.2ms)

Started DELETE "/users/1/edit"...

ActionController::RoutingError (No route matches [DELETE] "/users/1/edit")

Chrome调试器显示初始请求:

Request URL:http://localhost:3000/users/1/authorizations/12
Request Method:DELETE
Status Code:302 Found

并且其以下的重定向

Request URL:http://localhost:3000/users/1/edit
Request Method:GET
Status Code:404 Not Found

所以这似乎是浏览器正确地遵循重定向,但是rails忽略重定向调用上的GET,而是使用导致404的DELETE(因为DELETE不被该资源支持 – 这是错误的).

如果我简单地在重定向的URL上执行“GET”,它可以正常工作.

删除后,我缺少Rails的重定向?谢谢.

解决方法

这应该以更好的方式解决它:

redirect_to edit_user_path(params [:user_id]),状态:303

http://api.rubyonrails.org/classes/ActionController/Redirecting.html

If you are using XHR requests other than GET or POST and redirecting after the request then some browsers will follow the redirect using the original request method. This may lead to undesirable behavior such as a double DELETE. To work around this you can return a 303 See Other status code which will be followed using a GET request.

原文链接:https://www.f2er.com/ruby/271703.html

猜你在找的Ruby相关文章