LoginSignup
18

More than 5 years have passed since last update.

Rails ページ遷移元をコントローラで取得

Posted at

目標

ViewでRedirect_to等でページ遷移をおこなった時にViewで条件分岐をするのかControllerで条件分岐をするのかよく考えControllerが最適だと判断した
今回は、
ページ遷移が起こったとき、ページ遷移先のコントローラ内で、遷移元のコントローラ名を明示して変数を操る

補足

スポーツ関連のアプリで、試合(=Game)を組みたいもの。
ユーザーは基本的な利用では場所情報が入っているPlaceテーブルから最初に開催地を選択しparamsで場所idをとばして試合を組むが、
ユーザーは試合詳細ページから全く同じ条件(場所、参加条件等、 開催日以外)で簡単に試合を開催できる複製機能を設置したかった。

ソースコード

games_controller
def new 
 @path = Rails.application.routes.recognize_path(request.referer)
#games#showから遷移。試合の開催日以外は同じ条件で試合の予定を組みたい
 if @path[:controller] == "games"
  @game = Game.find(params[:id])
  @game.fight_time = Time.zone.now.beginning_of_hour;1.week 
 else #place#index等
  @game = Game.new(place_id: params[:id])
 end
end

参考ページ

https://qiita.com/sayama0402/items/ffe96ff76148231a0c22
↑ 取得方法について

http://ruby-rails.hatenadiary.com/entry/20141217/1418817120#activesuppor-time-prev-and-next
↑ railsでの時間の操り方

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
18