DELETEメソッド実行後のリダイレクトでNo route matches [DELETE]となってしまう


非同期処理で削除処理を行った後、リダイレクトを行うとメソッドがGETではなくDELETEとなってしまい正常にリダイレクトされない現象が発生したためメモ。

発生した状況

delete.js
// 一部抜粋
$.ajax({
  type: 'DELETE',
  url: '/posts/destroy_post',
  dataType: 'json',
  data: {
    post_id: $(this).data('post-id')
  }
}).done(function (data, status, xhr) {
  // 処理
});
posts_controller.rb
  # 一部抜粋
  def destroy_post
     # 処理

    redirect_to post_index_path
  end
// 発生エラー
ActionController::RoutingError (No route matches [DELETE] "/post"):

改善策

posts_controller.rb
  # 一部抜粋
  def destroy_post
     # 処理

    redirect_to post_index_path, status: 303
  end

上記のように「status: 303」と記載をすることで改善。

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.

GETまたはPOST以外のXHRリクエストを使用していて、リクエストの後にリダイレクトしている場合、一部のブラウザは元のリクエストメソッドを使用してリダイレクトに従います。これにより、二重DELETEなどの望ましくない動作が発生する可能性があります。これを回避するには、GETリクエストを使用して追跡される303 See Otherステータスコードを返すことができます。

上記のように二重DELETEが発生していたと思われる。
引数にStatusコード303を指定することにより、回避することができるようです。

参考

Rails Redirect After Delete Using DELETE Instead of GET

以上です。
いいねやQiitaやTwitterのフォローいただけると励みになります!
他にも方法がありましたら、コメントお待ちしております。
宜しくお願いします〜