Can someone explain why I woud use rails link_to etc instead of straight HTML code? Given that they will render the same once they get to the browser – what is the actual benefit here?
<a href="index.html"><img id="logo" src="images/logo.png" alt="logo" /></a>
<%= link_to image_tag("logo.png", :alt => "logo", :id => "logo"), root_path %>
Background – I was changing this in a template and stopped to think why am I doing this?
In Rails 3.1, using the helper method would make use of the asset pipeline. For the URLs, that means that the images are postfixed with a checksum (this is called fingerprinting, at least in the Rails guide linked above). That allows to set the HTTP server cache expiration to a maximum – if the file content changes, it will result in another filename and thus force redownloading the file. Otherwise it’ll be served from the browser cache.
Also, if you specify an asset host in your configuration, the helper methods will use this information – check out the documentation for
image_url.As for link_to, well, I suppose you could also do something like
<a href="<%= root_path %>">Link</a>, but using the ruby code is more elegant in my opinion.You should never hardcode the URL in HTML – it might change, and you really don’t want to go through your source code and change all references to
index.htmltohome.htmlor anything like that.