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.html
to home.html
or anything like that.
This is a great question. I consider it better practice to use the rails link_to
method as well as the other html helper methods. In this case, it may not have an clear advantage, but more times than not it does. Here are some cases where it is helpful:
Changing Routes
If you have a named route, say foo_path
which directs to /foo
. You can use <a href='/foo'>
, but if you wanted to change foo_path
to route to /foo_bar
- you would have to go through each view and manually change the links.
Variables
It is common to need a variable for a link. It is more elegant to have <%= link_to @foo.name, foo_path %>
than <a href='/foo'><%= @foo.name %></a>
Look and maintainability
In my experience, view code that utilizes helper methods tends to look better and is easier to refactor and maintain.
The helpers expose functionally you don't necessarily always use, like ":remote => true", or automatically including an app context, or bringing in the asset pipeline.
For the simplest use cases there is often little or no benefit, but that's not where helpers shine-they're for when things go cows-legs-up and the "raw" form includes logic too bulky to remain in the mainline template.
Using them for the simple use-cases keeps things consistent, and makes templates more resilient to change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With