How to Use Rails Helpers (Complete Guide)

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.

Here’s an example:

time_ago_in_words(Time.now)
# "less than a minute"

time_ago_in_words(Time.now + 60)
# "1 minute"

time_ago_in_words(Time.now + 600)
# "10 minutes"

This method is helpful whenever you want to display time in this specific format.

Another Rails view helper is number_to_human.

Example:

number_to_human(10_000)
# "10 Thousand"

This is great when you want to take a number & print it as you would read it, which makes it feel more human.

You can find more helpers in the Ruby on Rails documentation.

But did you know you can write your own?

Writing Your Own Helper Methods

If you’re looking to write custom helper methods, the correct directory path is app/helpers.

You write your helpers inside a helper module.

Every Rails application comes with a base helper module by default, it’s called ApplicationHelper.

Here’s where you can add your helper methods.

These methods become available to all your views automatically. Later you’ll learn how to use them in controllers & why that may be a bad idea.

You could write all your helpers in ApplicationHelper.

But there is another option…

You can create helper modules so you can better organize your methods.

Instructions:

  • Create a new file under app/helpers
  • Name it something like user_helper.rb
  • Add a new module which matches the file name

Example:

# app/helpers/user_helper.rb

module UserHelper
  def format_name(user)
    if user.gender == "M"
      "Mr. #{user.name}"
    else
      "Ms. #{user.name}"
    end
  end
end

This code can be used to address a person in a formal way based on their gender.

The main benefit?

You don’t have to repeat this logic in other views when you need it & when you need to change the code… it only has to change in one place.

Very nice!

Using Your New Helper Module

You can use your helper methods in your views.

Like this:

<%= format_name(@user) %>

Easy, right?

If you want to use helpers outside of views you’ll need something else.

How to Use Helpers From Controllers

It’s possible, although not very common, to use helper methods from controller actions.

Before Rails 5, you had to include the helper module.

In newer versions, you can use helpers in your controller with the helpers (plural) object.

Like this:

class UsersController
  def index
    helpers.time_ago_in_words(Time.now)
  end
end

This way you can use helpers from your controller. But think twice before doing this because it may be a design issue.

Consider using a plain Ruby object instead.

Fun With The Rails Console

I love using the Rails console (irb with your Rails app loaded) to try out methods & play around with things.

Helpers included!

You can use helpers from the console with helper.method_name.

Notice the singular form of “helper” so you don’t get an error message. And remember that the console doesn’t reload code changes automatically.

Best Practices for Writing Rails View Helpers

When should you create a helper method?

Whenever you have logic that produces bits of HTML.

Usually, this falls into one of two categories, one is string formatting & the other is conditional page elements.

Another tip…

If you want to write good helpers don’t use any instance variables, they may be available in your current view, but they may not be in another view.

That will result in an error because of missing variables.

The solution?

Use parameters, so any data your method needs is clear & explicit.

# wrong way

def eat_healthy
  @fruit.eat
end

# do this instead

def eat_healthy(fruit)
  fruit.eat
end

My final tip is to divide your helpers into modules, where each module name describes clearly what kind of methods it contains.

However:

This won’t help with duplicated method names, which can result in errors & confusion.

All your helpers should have unique names.

As an alternative, try using presenter objects, as explained in this guide.

Summary

You have learned about helpers in Rails! A set of utility methods you can use for formatting & handling complex logic in your views.

Now it’s time to create your own helpers.

Thanks for reading 🙂

14 thoughts on “How to Use Rails Helpers (Complete Guide)”

  1. For clarification, under the “Using Your New Helper Module” heading, you give <%= format_gender(@user) %> as the example, although the method you created above is format_name(user). Just pointing out a small error. Thanks for the article, and keep up the great work!

    • Thanks, but I believe that’s not an error. 🙂

      When you call a method with @user, you’re not passing in the variable, but the value of the variable.

  2. I don’t know why the built-in helpers aren’t working for me. Here’s my rails console feedback:

    [1] pry(main)> number_to_human(137)
    NoMethodError: undefined method number_to_human' for main:Object
    from (pry):1:in

    Same with time_ago_in_words(Time.now)

  3. I just used the following and it worked:
    helper.time_ago_in_words(Time.now) I’m in Rails 6 if that makes a difference.

Comments are closed.