fv17の日記

Webエンジニアの備忘用ブログです。主にWeb界隈の技術に関して書いています。

Rails - 名前付きルートにおける_pathと _urlの違いと使い分け

_pathは相対パスで、_urlは絶対パスである。

root_path -> '/'
root_url  -> 'http://www.example.com/'

使い分けとしては、

  • _path : 通常はこちらを使う。例えば、Viewにおける利用。
  • _url : redirect_toする場合のみ。主に、controllerにおいて用いられる。

HTTPの標準としては、リダイレクトのときに完全なURLが要求されるため。*1

参照

Stack Overflow

What is the difference between _url and _path while using the routes in rails - Stack Overflow

stackover flowで質問されていて、明確な理由が書かれている。

_path are for views because ahrefs are implicitly linked to the current URL. So it’d be a waste of bytes to repeat it over and over. In the controller, though, *_url is needed for redirect_to because the HTTP specification mandates that the Location: header in 3xx redirects is a complete URL.

Railsチュートリアル

https://railstutorial.jp/chapters/filling_in_the_layout?version=5.1#sec-rails_routes

rails tutorial内でも下記記載がある

一般的な規約に従い、基本的には_path書式を使い、リダイレクトの場合のみ_url書式を使うようにします。これはHTTPの標準としては、リダイレクトのときに完全なURLが要求されるためです。

*1:rails tutorialより。ただし、現在では多くのブラウザが相対パスにも対応しているとのこと。