ページにアクセスした際に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が策定された時にヘッダ名を間違ったスペルで書いてしまい、それが今でも使われている、という歴史的経緯のためである。
まとめ
[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”