LoginSignup
4
0

More than 3 years have passed since last update.

ユーザー新規登録備忘録 part3:遷移元のコントローラーとアクションを取得して、条件分岐をする

Last updated at Posted at 2019-10-28

~同じコントローラーのアクションを使って今いるページからのリンク先を変える方法~

起きていたこと

1.新規登録の時(修正前)

/signup/cards

cards.png
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

/card/show

show.png

2.カード情報を追加登録の時(修正前)

/card/new

new.png
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

/card/show

show.png

"1.新規登録"の時の遷移先を/signup/finishにしたいが
問題のコントローラーを確認すると/signup/finishに飛んでない!!**

card_controller.rb(修正前)
  def pay 
    Payjp.api_key = ENV["PAYJP_ACCESS_KEY"]
          [省略]
      if @card.save//保存できたら
        redirect_to action: "show"//カード情報を表示する
      else//保存できなかったら
        redirect_to action: "pay"
      end
    end
  end

やりたいこと

/signup/finishを設定してない遷移元のコントローラーとアクションを指定して条件分岐できないだろうか?
=>会員登録の時とユーザー設定ページのそれぞれでcardコントローラーでnewを使用したした時で分けたい
理想形.png

結論:request.referrerを使用する

request.referrerの例
遷移元のコントローラーを取得
Rails.application.routes.recognize_path(request.referrer)
 {:controller=>"users", :action=>"index"}

こちらで遷移元の URL が取得できる
request.referrer
 "http://localhost:3000/users"

=========================================

request.referrerを実装する

card_controller.rb(修正後)
  def pay 
    Payjp.api_key = ENV["PAYJP![cards.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/487723/8eae145d-f132-acff-0c61-a44229d99489.png)
_ACCESS_KEY"]
          [省略]
       path = Rails.application.routes.recognize_path(request.referer)
        if path[:controller] == "card" && path[:action] == "new" //もしも、"card"コントローラでnewを行ったら、
          redirect_to action: "show" //showを行う
        else //違ったらfinishへ飛ばす
          redirect_to finish_signup_index_path
        end
          [省略]

修正した結果

1.新規登録の時(修正版)

/signup/cards

cards.png
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

/signup/finish

finish.png
falseで読み込まれるため/signup/finishへ飛ぶ

実行したところ
        else //違ったらfinishへ飛ばす
          redirect_to finish_signup_index_path

2.カード情報を追加登録の時

trueのためこちらの結果は修正前と変わらない

参考記事

https://qiita.com/sayama0402/items/ffe96ff76148231a0c22
http://kawahiro.hatenablog.jp/entry/2014/03/21/164449

4
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
4
0