Rails Helper Method

Helper methods allow controller methods to be called in the associated layout code.

  # UserController

  helper_method def current_user
    @current_user ||= User.find(params[:id])
  # User Show Page

  <h1>Hello, <%= current_user %></h1>

Why use a helper_method?

A helper method is advantageous to use over an instance variable in a variety of ways.

  1. Instance variable value is set to nil which can lead to unexpected results
  def test

  # test == nil
  1. Instance variables are more difficult to maintain due to tracking of read and write, especially when @object is used in many places

  2. Helper methods can return a more useful stack trace

  3. Helper methods keep controller actions DRY

  def edit

  def update

  def show

  helper_method def active_record_object
    @object ||= ActiveRecordObject.find(params[:id])

I recommend replacing instance method calls with helper_method’s in your Rails code!

comments powered by Disqus