Вопрос

I have a route I am issuing a DELETE on:

user_authorization_path(@user, authorization)

It hits my controller fine, the controller deletes the resource, and then issues a redirect:

redirect_to edit_user_path(params[:user_id])

The result of this is a routing error on redirect:

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

I can see in the logs rails is doing the right thing until the redirect, which it is trying to issue another DELETE instead of a 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")

The Chrome debugger shows the initial request:

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

And its following of the redirect:

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

So this appears to be that the browser is following the redirect correctly, but rails is ignoring the GET on the redirect call and instead using DELETE which results in 404 (since DELETE is not supported by that resource - which is wrong anyway).

If I simply do a 'GET' on the redirected URL, it works fine.

What am I missing about Rails' redirect after delete? Thanks.

Это было полезно?

Решение

This should fix it in a nicer way:

redirect_to edit_user_path(params[:user_id]), status: 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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top