20
8

More than 3 years have passed since last update.

[Rails]コントローラ名、アクション名、URLなどを取得する

Last updated at Posted at 2019-12-20

ページにアクセスした際にRails側で

  • コントローラ名
  • アクション名
  • URL

などを取得します。

想定する状況

マイページ(http://localhost:3000/mypage)
から
記事投稿画面(http://localhost:3000/articles/new)
に移動したときにコントローラでbinding.pryを使って処理を止めてみます。

コントローラ名

controller_name

[1] pry(#<ArticlesController>)> controller_name
=> “articles”

アクション名

action_name

[2] pry(#<ArticlesController>)> action_name
=> “new”

HTTPメソッド名

request.method または request.request_method

[3] pry(#<ArticlesController>)> request.method
=> “GET”
[4] pry(#<ArticlesController>)> request.request_method
=> “GET”

アクセスするURL

request.original_url

[5] pry(#<ArticlesController>)> request.original_url
=> “http://localhost:3000/articles/new”

アクセスするURL(ドメイン省略)

request.fullpath

[6] pry(#<ArticlesController>)> request.fullpath
=> “/articles/new”

直前のページ

request.referer

[7] pry(#<ArticlesController>)> request.referer
=> “http://localhost:3000/mypage”

refererだよ。referrerじゃないよ。

本来、参照元という意味の英単語は「referrer」であるが、HTTPリファラの場合は意図的に「referer」と綴る場合がある。これは、HTTPが策定された時にヘッダ名を間違ったスペルで書いてしまい、それが今でも使われている、という歴史的経緯のためである。

 HTTPリファラ - Wikipediaより

まとめ

[1] pry(#<ArticlesController>)> controller_name
=> “articles”
[2] pry(#<ArticlesController>)> action_name
=> “new”
[3] pry(#<ArticlesController>)> request.method
=> “GET”
[4] pry(#<ArticlesController>)> request.request_method
=> “GET”
[5] pry(#<ArticlesController>)> request.original_url
=> “http://localhost:3000/articles/new”
[6] pry(#<ArticlesController>)> request.fullpath
=> “/articles/new”
[7] pry(#<ArticlesController>)> request.referer
=> “http://localhost:3000/mypage”
20
8
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
20
8