helper_method in Rails

The method helper_method is to explicitly share some methods defined in the controller to make them available for the view. This is used for any method that you need to access from both controllers and helpers/views (standard helper methods are not available in controllers). e.g. common use case:

#application_controller.rb
def current_user
  @current_user ||= User.find_by_id!(session[:user_id])
end
helper_method :current_user

the helper method on the other hand, is for importing an entire helper to the views provided by the controller (and it’s inherited controllers). What this means is doing

# application_controller.rb
helper
:all

Another example:

class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :authenticate_user!
helper_method :current_user, :logged_in?

def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end

def logged_in?
!!current_user
end

protected

  def authenticate_user!
redirect_to root_path unless logged_in?
end
end

 

Note: these few methods for authenticating a user could be defined in a separate session helper module.

Below is from Rails API documentation

helper_method(*meths)

Declare a controller method as a helper. For example, the following makes the current_user and logged_in? controller methods available to the view:

class ApplicationController < ActionController::Base
  helper_method :current_user, :logged_in?

  def current_user
    @current_user ||= User.find_by(id: session[:user])
  end

  def logged_in?
    current_user != nil
  end
end

In a view:

<% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>

Parameters

  • method[, method] – A name or names of a method on the controller to be made available on the view.