views:

86

answers:

2

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?

+5  A: 

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.

Adam Vandenberg
+6  A: 

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/"&gt;Google&lt;/a&gt;
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.

Matchu