Named routes _path vs _url

前端 未结 4 2037
借酒劲吻你
借酒劲吻你 2020-11-29 20:27

Rails provides named routes.

Routes helper can be called using path or url

eg from docs:

# and provide these named routes
root_url   # =>          


        
相关标签:
4条回答
  • 2020-11-29 20:31

    _path provides relative path.

    _url provides absolute path.

    Whenever you send a URL in email etc. than it is a best practice to use _url instead of _path.

    0 讨论(0)
  • 2020-11-29 20:34

    _path helpers provide a site-root-relative path. You should probably use this most of the time.

    _url helpers provide an absolute path, including protocol and server name. I've found that I mainly use these in emails when creating links to the app on the server. They should mainly be used when providing links for external use. (Think email links, RSS, and things like the copy and paste URL field under a YouTube video's "Share" section.)

    0 讨论(0)
  • 2020-11-29 20:34

    As the other answers explain, you should use _url in email links, etc. But I would like to add that you should also use _url in redirects, as explained here:

    https://www.ruby-forum.com/topic/101346#221052

    and, here:

    http://viget.com/extend/rails-named-routes-path-vs-url

    You can also take a look at the relevant section of the HTTP specification here:

    http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30

    0 讨论(0)
  • 2020-11-29 20:39

    When you put a link in your own site, the domain part of the route is redundant, and adds to the page size, so you can just use the path part of the URL with the *_path helper. On the other hand, if the URL is to be consumed outside of your site, e.g. an email or an RSS feed, the whole URL is needed, so use the *_url helper.

    0 讨论(0)
提交回复
热议问题