Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Rails use helper methods like link_to instead of <a href...>?

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?

like image 669
ab217 Avatar asked Oct 17 '10 01:10

ab217


People also ask

What are Rails helpers?

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 .

How do I link pages in Rails?

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.

What is link_ to in Rails?

link_to is a Rails built in helper that helps generate an anchor tag.


2 Answers

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.

like image 136
Matchu Avatar answered Oct 22 '22 02:10

Matchu


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.

like image 22
Adam Vandenberg Avatar answered Oct 22 '22 03:10

Adam Vandenberg