I am learning Rails and I have noticed that Rails continously uses helper method such as link_to
instead of just using plain html. Now I can understand why they would use they would use some helper methods, but I don't understand why they would prefer helper methods over just coding the html directly. Why does Rails prefer helper method instead of you having to write the html manually? Why did the Rails team make this design choice?
What are helpers in Rails? A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words .
Instead of using the anchor ( <a> ) HTML tags for links, Rails provides the link_to helper to add links. Remember, Ruby code in the views must be enclosed in a <% %> or a <%= %> tag.
link_to is a Rails built in helper that helps generate an anchor tag.
In Rails apps, links are often generated using both methods for URL and methods for content, e.g.
<%= link_to @article.user.name, @article.user %>
That's definitely more manageable than putting those into the <a>
tags manually.
<a href="<%= user_path(@article.user) %>"><%= @article.user.name %></a>
(You are using the router for generating those URLs, right? What happens if you hardcode /users/1
and decide that you want it to be /users/1-John-Doe
later?)
For static links, though, it doesn't really matter much.
<a href="http://www.google.com/">Google</a>
or
<%= link_to 'Google', 'http://www.google.com/' %>
One could make a case for the former for performance or the latter for consistent style, since both are equally manageable.
If the URL routing for a model changed, then hand-written HTML would all have to be updated as well; by going through a function the behavior (link to one of these things) is decoupled from the current routing scheme.
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