Rails Helpers — View Helper Methods and Modules
In this tutorial, you will learn about Rails Helpers. We cover key concepts, practical examples, and best practices to help you master this topic.
Rails helpers are modules providing view-related methods for formatting dates, generating URLs, creating forms, handling text, and managing assets.
What You'll Learn
By the end of this tutorial, you'll use built-in Rails helpers, create custom helpers, use form and asset helpers, organize helper methods, and test helpers.
Why Helpers Matter
Helpers keep presentation logic out of templates. Built-in helpers handle common patterns like link_to, form_for, number_to_currency, and pluralize.
Real-World Use
An e-commerce site uses number_to_currency for prices, distance_of_time_in_words for relative dates, custom helpers for product badges, and asset helpers for image variants.
Helpers Path
flowchart LR
A[Rails Views] --> B[Helpers]
B --> C[Form Helpers]
B --> D[Asset Helpers]
B --> E[Text Helpers]
B --> F[Custom Helpers]
B --> G{You Are Here}
style G fill:#f90,color:#fff
Built-in Helpers
Common built-in helper methods.
<%# app/views/products/show.html.erb %>
<h1><%= @product.name %></h1>
<p><%= number_to_currency(@product.price) %></p>
<p><%= pluralize(@product.reviews.count, "review") %></p>
<p>Added <%= time_ago_in_words(@product.created_at) %> ago</p>
<p><%= truncate(@product.description, length: 100) %></p>
<p><%= highlight(@product.description, @query) %></p>
<p><%= simple_format(@product.description) %></p>
Form Helpers
Build forms with Rails form helpers.
<%= form_with model: @product, local: true do |form| %>
<% if @product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.errors.count, "error") %></h2>
<ul>
<% @product.errors.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :price %>
<%= form.number_field :price, step: 0.01 %>
</div>
<div class="field">
<%= form.label :category_id %>
<%= form.collection_select :category_id, Category.all, :id, :name %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
Custom Helpers
Create your own helper methods.
# app/helpers/products_helper.rb
module ProductsHelper
def product_status(product)
if product.published?
tag.span "Published", class: "badge bg-success"
elsif product.draft?
tag.span "Draft", class: "badge bg-warning"
else
tag.span "Archived", class: "badge bg-secondary"
end
end
def product_price_with_discount(product)
if product.on_sale?
content_tag :div, class: "price" do
concat tag.span number_to_currency(product.original_price), class: "original"
concat tag.span number_to_currency(product.sale_price), class: "sale"
end
else
number_to_currency(product.price)
end
end
def star_rating(rating)
full_stars = rating.floor
half_star = rating - full_stars >= 0.5
content_tag :div, class: "stars" do
(1..5).map do |i|
if i <= full_stars
tag.i class: "fas fa-star"
elsif i == full_stars + 1 && half_star
tag.i class: "fas fa-star-half-alt"
else
tag.i class: "far fa-star"
end
end.join.html_safe
end
end
end
Asset Helpers
Manage CSS, JavaScript, and image assets.
<%= stylesheet_link_tag "application", media: "all", "data-turbo-track": "reload" %>
<%= javascript_include_tag "application", "data-turbo-track": "reload", defer: true %>
<%= image_tag "logo.png", alt: "Logo", size: "200x50" %>
<%= favicon_link_tag "favicon.ico" %>
<%= video_tag "intro.mp4", controls: true, autoplay: true %>
URL and Link Helpers
Generate URLs and links.
<%= link_to "Products", products_path %>
<%= link_to @product.name, @product %>
<%= link_to "Edit", edit_product_path(@product), class: "btn btn-primary" %>
<%= link_to "Delete", @product, method: :delete, data: { confirm: "Are you sure?" } %>
<%= button_to "Add to Cart", add_to_cart_path(@product), method: :post %>
<%= mail_to "support@example.com", "Contact Support" %>
Common Mistakes
1. Writing HTML in Helpers
Helpers should generate HTML with tag helpers, not concatenate strings.
2. Helper Methods That Query the Database
Helpers are for presentation. Database queries belong in models or controllers.
3. Not Using Built-in Helpers
Implementing custom format_date when distance_of_time_in_words exists.
4. Helper Name Collisions
Common method names in helpers may override Rails built-ins. Check method names.
5. Testing Helpers Without Views
Helpers can be unit tested directly using helper object in RSpec.
Practice Questions
1. What helper formats a number as currency?
number_to_currency.
2. How do you create a link in Rails?
Use link_to "Text", path.
3. What is the difference between link_to and button_to?
link_to creates an anchor tag. button_to creates a form with a submit button.
4. How do you pluralize a word in Rails?
Use pluralize(count, "word").
5. Challenge: Create a helper that formats user profile details.
module UsersHelper
def user_avatar(user, size: 40)
if user.avatar.attached?
image_tag user.avatar.variant(resize: "#{size}x#{size}"), class: "avatar"
else
tag.div user.initials, class: "avatar-initials", style: "width: #{size}px; height: #{size}px"
end
end
def user_joined_date(user)
content_tag :small, "Member since #{l user.created_at, format: :long}"
end
end
FAQ
Mini Project: Product Display Helpers
Create helpers for a product display page.
module ProductsHelper
def product_gallery(product)
content_tag :div, class: "gallery" do
product.images.map do |image|
concat image_tag image.variant(:medium), class: "gallery-image", data: { index: image.id }
end
end
end
def product_availability(product)
if product.in_stock?
tag.span "In Stock (#{product.quantity} available)", class: "text-success"
else
tag.span "Out of Stock", class: "text-danger"
end
end
end
What's Next
Rails Partials Collections Rails Views Deep Rails Layouts Partials
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro