LoginSignup
14
10

More than 5 years have passed since last update.

擬似的にPOSTでリダイレクトする

Last updated at Posted at 2016-02-29

諸事情により POST で受けて POST へリダイレクトする必要が生じたのですが、どうやら一筋縄ではいかないようです。

そこで、応急処置として自動で submit する form を利用して擬似的に POST を POST でリダイレクトさせてみました。

実装例

creat アクションのあと、POST で 完了画面を描画するという処理を実装してみます。

From

特定の URL へ自動で submit するだけの必要最低限のものを準備します。

app/views/shared/redirect_form.html.slim
doctype html
html
  head
  body onLoad="document.forms[0].submit()"
    = form_tag @redirect_path

Controller

リダイレクト先の URL を渡し、redirect 用 form を render します。
この先、layout は不要ですので、false を渡しておきます。

app/controllers/hoges_controller.rb
class HogesController < ApplicationController
  def create
    @hoge = Hoge.create(hoge_params)

    if @hoge.save
      @redirect_path = completed_hoges_path
      render "shared/redirect_form", layout: false
    else
      render :new
    end
  end
end

Routes

本題と関係ないですが、描画する complete アクションは以下のように設定しています。

config/routes.rb
Rails.application.routes.draw do
  resources :hoges do
    collection do
      post "completed", to: "hoges#complete"
    end
  end
end

これで、僅かに白い画面が描画された後、/hoges/completed へ POST リクエストが送られる、POST での擬似的なリダイレクトが実現できました。

まとめ

邪道感は拭えませんが、手間はかなり少ない手法だと思います。

また、世の中の POST 後に一瞬だけ白くなって完了画面に遷移するサイトって、このへんの POST で受けて POST で別ページを表示したい都合なのかなぁとやってて思いました。

もう少しスマートな方法がありましたらご教示ください :bow:

14
10
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
14
10