Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท Views and Templates

View Helpers

Learn Rails view helpers: link_to, content_tag, tag attributes, text and number helpers, and how to write your own helper methods. Includes a runnable helper stand-in with safe escaping.

A view helper is a small Ruby method you call from a template to generate HTML or format a value. Instead of writing <a href="/articles/1"> by hand, you write link_to "Read", article_path(article). Helpers keep templates short, make HTML consistent, and, most importantly, escape user data correctly.

Rails ships with dozens of helpers, and you can add your own in app/helpers. The Rails code in this lesson is read-only because the framework is not available in the browser. The runnable examples are plain Ruby stand-ins that rebuild the same ideas with the standard erb library, so you can see what a helper really does.

The helpers you will use every day

Most helpers fall into a few groups. Here are the common ones as read-only ERB:

ERB
<%# read-only: links and URLs %>
<%= link_to "All articles", articles_path %>
<%= link_to "Edit", edit_article_path(@article), class: "btn" %>
<%= link_to "Delete", @article, data: { turbo_method: :delete, turbo_confirm: "Sure?" } %>
<%= link_to_unless_current "Home", root_path %>
<%= mail_to "[email protected]", "Email us" %>

<%# read-only: tags %>
<%= content_tag :div, "Hello", class: "note", id: "greeting" %>
<%= tag.div "Hello", class: "note" %>
<%= tag.p class: "lead" do %>Longer content here<% end %>
<%= image_tag "logo.png", alt: "Logo", width: 120 %>

<%# read-only: text and numbers %>
<%= truncate(@article.body, length: 80) %>
<%= pluralize(3, "comment") %>             <%# "3 comments" %>
<%= simple_format(@article.body) %>        <%# wraps paragraphs in <p> %>
<%= number_to_currency(1234.5) %>          <%# "$1,234.50" %>
<%= number_with_delimiter(1234567) %>      <%# "1,234,567" %>
<%= time_ago_in_words(@article.created_at) %> ago
<%= l(@article.created_at, format: :short) %>

tag.div (the tag builder) is the modern way to write HTML tags; content_tag still works and you will see it in older code. Hash options such as class: and id: become attributes, and a data: { ... } hash becomes data-* attributes.

Escaping is automatic

When a helper builds HTML, Rails marks the result as safe (a SafeBuffer), while any plain string you pass in is escaped. That is why tag.p("<script>") prints harmless text. Two rules follow from this:

  • Never call html_safe or raw on user input; it switches the protection off.
  • If you need user-provided HTML (for example a rich-text field), run it through sanitize, which removes dangerous tags and attributes.
ERB
<%# read-only %>
<%= sanitize(@comment.body, tags: %w[b i a], attributes: %w[href]) %>

You will meet this again in web security.

What a helper does

Builds HTML link_to, tag, image_tag.
Formats values Money, dates, plurals.
Escapes safely User text stays text.
1 / 2

Stand-in: building a tiny helper module

This stand-in implements tag, link_to and pluralize. It escapes values with ERB::Util.html_escape, which is the same function Rails uses under the hood. Run it and look at how the quote and the <script> text are made safe.

Ruby Stand-in: tag, link_to and pluralize

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice that the content is always escaped, including the attribute values. The only way to put raw HTML into the page would be to skip h, and that is exactly what you must avoid with user data.

Numbers, text and time

Formatting helpers are plain Ruby under the hood. The next stand-in rebuilds three of them so you understand what they do, and where the real ones go further (locales, options, currency units).

Ruby Stand-in: number_with_delimiter, truncate, time_ago_in_words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Writing your own helpers

Any method in a module under app/helpers is available in every view. By convention ArticlesHelper serves the articles views, but Rails includes all helper modules everywhere by default.

Ruby
# app/helpers/application_helper.rb  (read-only)
module ApplicationHelper
  def page_title(text = nil)
    [text, "My Blog"].compact.join(" | ")
  end

  def status_badge(article)
    css = article.published? ? "badge-green" : "badge-gray"
    tag.span article.status.humanize, class: ["badge", css]
  end
end
ERB
<%# read-only %>
<title><%= page_title(@article&.title) %></title>
<%= status_badge(@article) %>

Note that class: accepts an array and Rails joins it with spaces. Good helpers are short, take their data as arguments (not instance variables), and return a string. If a helper grows to dozens of lines or needs its own state, consider a partial, a presenter object or a ViewComponent.

Helpers are plain Ruby, so test them like plain Ruby: call the method and compare the string. Rails also gives you ActionView::TestCase for helper tests, which you will meet in testing.

Common mistakes

  • Building HTML with string interpolation: "<a href='#{url}'>#{label}</a>" skips escaping. Use link_to.
  • Calling html_safe on a string that contains user data.
  • Putting business rules in helpers. Helpers format; models decide.
  • Reading @article inside a helper. Pass it as an argument so the helper works anywhere.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does link_to "Read", article_path(article) produce?

    link_to returns an anchor tag; the second argument becomes the href.
  2. 2. What happens when you pass <script> text to tag.p?

    Helpers escape plain strings, so user input cannot inject HTML.
  3. 3. Where do you put your own helper methods?

    Modules in app/helpers are available in all views.
  4. 4. Why should a helper receive data as arguments instead of reading @article?

    Explicit arguments make a helper reusable and testable.

Summary

  • Helpers are Ruby methods that build HTML or format values for views.
  • link_to, tag, image_tag, pluralize, truncate and the number_to_* family cover most needs.
  • Helpers escape plain strings; avoid html_safe and raw on user data and use sanitize for rich text.
  • Your own helpers live in app/helpers, take explicit arguments and stay small.

Next: Hotwire: Turbo and Stimulus