我有一个路由,我正在发出一个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”,它可以正常工作.
解决方法
这应该以更好的方式解决它:
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.