<= Home
Named Routes: When _url is better then _path
After you configure a resource in your rails routes configuration, you have access to generate named routes with _path and _url. The main difference between _url and _path can be demonstrated in the following example.
map.resource :people
we can now do the following:
person_path(@person) #=> /people/1 person_url(@person) #=> http://localhost:3000/people/1
_path versus _url
So when do we use one over the other?
The current school of thought is that in the view we use _path (i.e. person_path) as everything is relative to the current url. When we need to do any redirection in the controllers we would use _url (i.e. person_url) because the browser needs a absolute url for redirection.
The perceived advantage of relative paths (_path) in our view is that the less characters you have like href="/people/1" over href="http://localhost:3000/people/1" then therefore less the bytes that have to be passed across the wire. That is good to note but by using _path in views you are potentially setting yourself up for some problems. Primarily reverse proxy issues that still continue to plague rails. If our rails application is sitting on a server, lets say http://app1.server.com, but we have it behind a load balancer and other various reverse proxies (i.e. single sign on) so that it is publicly accessible with url of "http://my.doman.com/rails-app/" then we will have some troubles. There are several issues to note with the reverse proxy problems and there are various solutions but for the sake of staying on topic lets only look at the _path _url problem. Standard views generally are fine with relative paths as they will generate '/person/2' so the browser typically will look at the url in our example as "http:/my.coman.com/rails-app/people/1". But any view rendered from an ajax request is going to look to the browser like "http:/my.coman.com/people/1" omitting the sub directory "rails-app".
My suggestion is that if you are not 100% sure of your deployment environment when initially developing a rails application, program a little more defensively for the sake of a couple bytes and use _url named routes instead of _path for all urls. By doing this you can be a little more prepared to adapt to your production environments as all the reverse proxy fixes will only work with absolute urls and not relative ones.