1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

redirect_toで間接的にpostリクエストを出す方法

Last updated at Posted at 2019-11-12

はじめに

redirect_toを用いてpostリクエストでリダイレクトしたいが、仕様上不可能とのこと。
ただどうしても、上記形を取りたい!という方向けに、**”力ずく”**で間接的にpostリクエストを出す実装方法を考えましたので記します。

流れ

まず仕様上、redirect_toで直接postリクエストを出すことはできないので、getリクエストを出すこととします。
下記はトーナメント方式のアプリを実装時に、1回戦で負けた際に2回戦の試合結果を自動的にデータベースに保存するという流れを取っています。1回戦で敗北した際に、first_round_controllerのrecordアクションから、second_round_controllerのloseアクションをgetリクエストでリダイレクトさせています。

first_rounds_controller.rb
class FirstRoundsController < ApplicationController
  def record
   (省略)
    difference = @RRecord.point_difference
    if difference > 0 
     redirect_to new_player_second_round_path   #1回戦勝利時(getリクエスト)
    else
     redirect_to lost_player_second_rounds_path   #1回戦敗北時(getリクエスト)
    end
  end
end
second_rounds_controller.rb
class SecondRoundsController < ApplicationController
  def new #1回戦勝利時(getリクエスト)
  end

  def lose #1回戦敗北時(getリクエスト)
  end

  def lose_record #1回戦で敗北した時にSecondRoundテーブルに自動的にデータをセーブ(postリクエスト)
    SecondRound.create(
      カラム1: "hoge",
      カラム2: "hoge",
      カラム3: "hoge",
      カラム4: "hoge"
    )
  end
end

敗北時、getリクエストを出すためloseアクションに伴う、lose.html.hamlが表示されますが、こちらには下記のように記述するだけで画面は何も記載されていない白画面のままです。form_withのurlはsecond_rounds_controllerのlose_recordアクション(postリクエスト)を指定します。

lose.html.haml
= form_with url: lost_record_player_second_rounds_path, method: :post

このままではlose.html.hamlの白画面で止まったままですので、form_withで指定したurlに遷移するようにJSを以下のように設定します。

page_transition.js
$(document).on("turbolinks:load", function(){
  if (location.href.match("/[a-zA-Z0-9_]+/lose$")){
    document.forms[0].submit();
  }
})

今回はページのパスが....../loseの時にlose.html.hamlのform_withがsubmitされて、second_rounds_controllerのlose_recordアクション(postリクエスト)が呼び出されることになります。これでredirect_toで間接的にpostリクエストを出すことができます。

まとめ

以上がredirect_toで間接的にpostリクエストを出す方法です。getリクエストを出したのちにpostリクエストを出すため、一時的に画面を読み込んでいるようなページ(白画面)が表示されますが、目的は達成できるかと思います。他に良い方法がありましたらぜひご教示ください。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?