0
0
RailsHow-ToBeginner · 3 min read

How to Use Helpers in Rails: Syntax and Examples

In Rails, helpers are modules that hold methods to keep your views clean and DRY. You use them by defining methods in helper files (like app/helpers/application_helper.rb) and calling those methods in your views with <%= helper_method %> or directly in templates.
📐

Syntax

Helpers in Rails are Ruby modules where you define methods to use in views. You create a helper method inside a helper module, usually in app/helpers. Then you call the method in your view templates.

Example parts:

  • Module: Groups helper methods.
  • Method: Defines reusable code.
  • View call: Use method name to insert output.
ruby
module ApplicationHelper
  def greeting(name)
    "Hello, #{name}!"
  end
end

# In a view (e.g., app/views/home/index.html.erb):
<%= greeting('Alice') %>
Output
Hello, Alice!
💻

Example

This example shows how to create a helper method that formats dates nicely and use it in a view.

ruby
module ApplicationHelper
  def formatted_date(date)
    date.strftime("%B %d, %Y")
  end
end

# In a view (app/views/posts/show.html.erb):
<%= formatted_date(@post.created_at) %>
Output
April 27, 2024
⚠️

Common Pitfalls

Common mistakes when using helpers include:

  • Defining helper methods in controllers instead of helper modules.
  • Trying to use helper methods in models (which breaks MVC).
  • Not restarting the server after adding new helper methods in development.
  • Using instance variables inside helpers without passing them explicitly.

Always keep helpers focused on view logic and keep business logic in models or controllers.

ruby
module ApplicationHelper
  # Wrong: Using controller instance variable directly
  def show_user_name
    @user.name
  end

  # Right: Pass user as argument
  def show_user_name(user)
    user.name
  end
end
📊

Quick Reference

ActionHow to Do It
Create helper methodDefine method inside a helper module in app/helpers
Use helper in viewCall method with <%= method_name(args) %> in .erb files
Access controller helpersHelpers are automatically available in views
Test helper methodsWrite tests in spec/helpers or test/helpers
Keep helpers cleanPut only view-related code, avoid business logic

Key Takeaways

Define helper methods inside modules in app/helpers to keep views clean.
Call helper methods in views using <%= method_name %> syntax.
Avoid putting business logic in helpers; keep them focused on presentation.
Pass needed data as arguments to helpers instead of relying on instance variables.
Restart the Rails server if new helpers don’t appear during development.