LoginSignup
63
61

More than 5 years have passed since last update.

【Rails】ajax通信 -> 処理 -> redirect_toのやり方(remote: true/controller)

Last updated at Posted at 2015-11-18

シチュエーション

View

page_a.html.erb

<%= link_to "エイジャックス", ajax_method_hoge_path, remote: true %> 

Controller


class HogeControlller
  def page_a
  end

  def ajax_method
    # do something
    redirect_to fuga_hoge_path
  end
end

↑こういう事したい。でも出来ない。こういう状況有りますよね。

※ちなみにこういう処理をしたい時に同時に悩むのが、link_toにparamsを持たせる方法ですが、以下を参考にして下さい。
【Rails】link_toにparamsを持たせる方法

しかし、remote: trueとoptionを指定しているので非同期通信になってしまい、View側で特定のページに遷移することはありません。

そこで、以下の方法で簡単に解決できます。

解決策

概要

  • Viewディレクトリは全くいじりません。
  • AjaxHelperというモジュールを作ります。
  • HogeControllerを少しいじります。

View

なにもいじらない。
hoge/ajax_method.js ファイルも作らなくて良い。

Module

app/controllers/concerns/ajax_helper.rb

module AjaxHelper
  def ajax_redirect_to(redirect_uri)
    { js: "window.location.replace('#{redirect_uri}');" }
  end
end

Controller


class HogeControlller
  # 先ほど作ったModuleをincludeします。
  include AjaxHelper 

  def page_a
  end

  def ajax_method
    # do something
    # ↓これは使いません。
    # redirect_to fuga_hoge_path

    # 以下追加
    respond_to do |format|
      format.js { render ajax_redirect_to(fuga_hoge_path) }
    end
  end
end

これでいけます。

63
61
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
63
61