Share This Article
Rails helpers are methods defined in your controller or view files.
They are used to format data before displaying it to the user or to create dynamic HTML elements.
You can create your own helpers throughout your application or use the built-in helpers provided by Rails.
Using Rails Helpers
To use a helper method, you can call it from any view file like this:
<%= helper_method %>
For example, if you have a helper method named format_date
, you can call it like this:
<%= format_date(@date) %>
Creating Your Own Helper Methods
You can create your own helper methods in your controller or view files.
For example, let’s say you want to create a helper method to format dates like this:
<%= format_date(@date) %>
The format_date
helper method could look like this:
def format_date(date)
date.strftime("%d/%m/%Y")
end
You could also put this helper method in a file like this:
app/helpers/application_helper.rb
And then, you can call it from any view file in your application.
Rails Built-in Helpers
Rails provides many helpful methods you can use in your views.
For example, let’s say you want to create a link to another page in your application.
You can use the link_to
helper method to do this.
<%= link_to "Home", root_path %>
The link_to
helper method takes two arguments, the first one is the link text, and the second is the path to the page you want to link to.
You can also use the link_to
helper method to create links to actions in your controllers.
For example, let’s say you have a controller called ArticlesController
with an index
action.
You can easily create a link to this action using the link_to
helper method like this:
<%= link_to "Articles", articles_path %>
The articles_path
helper method is created by Rails and it returns the path to the index
action in the ArticlesController
.
Rails also provides helper methods for things like:
- Creating forms
- Generating URLs
- Sanitizing HTML
- Working with JavaScript
You can find a complete list of Rails helper methods in the Rails API documentation
Summary
In this article, you’ve learned about Rails helpers, how to use them and how to create your own helper methods. You’ve also learned about the different helper methods that are provided by Rails.
If you want to learn more about Ruby on Rails, I have a course that covers everything you need to know to build web applications with Rails.
You can check it out here:
https://www.letsbuildwebsites.com/courses/lets-build-a-website-with-ruby-on-rails