Rails - Helpers


What is the purpose of the link_to helper?

<%= link_to 'My Blog', controller: 'articles' %>

The link_to method is one of Rails' built-in view helpers. It creates a hyperlink based on text to display and where to go - in this case, to the path for articles.

Let's add links to the other views as well, starting with adding this "New Article" link to app/views/articles/index.html.erb:

<%= link_to 'New article', new_article_path %>

Also add a link in app/views/articles/new.html.erb, underneath the form, to go back to the index action:

<%= link_to 'Back', articles_path %>

Finally, add another link to the app/views/articles/show.html.erb template to go back to the index action as well, so that people who are viewing a single article can go back and view the whole list again:

<%= link_to 'Back', articles_path %>

When using the link_to helper, why do we sometimes use the controller option and why do we sometimes not use it?

If you want to link to an action in the same controller, you don't need to specify the :controller option, as Rails will use the current controller by default.

What is pluralize?

pluralize is a rails helper that takes a number and a string as its arguments. If the number is greater than one, the string will be automatically pluralized.

<%= pluralize(@article.errors.count, "error") %>
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License