LoginSignup
23
26

More than 5 years have passed since last update.

Railsで遷移元のcontroller、action名などを取得する方法とエラー対応

Last updated at Posted at 2018-08-14

はじめに

Railsで遷移元(直前)のcontrollerやaction名を取得するやり方について説明する。また、途中でエラーのため詰まった部分があったので、その時の対処法も記しておく。

やり方

controller
path = Rails.application.routes.recognize_path(request.referer)

これだけです。
個別にcontrollerやactionを呼び出したいときは以下。

controller
#controllerを取得
path[:controller]

#actionを取得
path[:action]

エラー対応

No route matchesというエラーが発生。

controller
before_uri = URI.parse(request.referer)
path = Rails.application.routes.recognize_path(before_uri.path)

これで解決した。

23
26
1

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
23
26