How to use view helper in controller and use controller method in view ?

Use view helper in controller?

Let’s say we have a helper method

module UsersHelper
def full_name(user)
user.first_name + user.last_name
end
end

How can we use the method in our controller?

Before Rails 5, you have to include the whole module(UsersHelper here) to use the method. But the problem here is do we really need all the methods in the module?

In Rails 5, you can use the helpers to access helpers methods outside the view.

module UsersHelper
def full_name(user)
user.first_name + user.last_name
end
end

class UsersController < ApplicationController

def update
@user = User.find params[:id]
if @user.update_attributes(user_params)
notice = "#{helpers.full_name(@user) is successfully updated}"
redirect_to user_path(@user), notice: notice
else
render :edit
end
end
end

The purpose of helpers is: Provides a proxy to access helpers methods from outside the view.

Resource: Rails 5 adds helpers method in controllers to ease usage of helper modules in controllers

Use controller method in view

We just introduced how to use view helper in controller, but how can we use controller method in view.

That’s say we have the current_user and logged_in? method in ApplicationController to check the status of user.

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
  def logged_in?
!!current_user
end
end

If we want these 2 methods are available in view, we can use the helper_method to help us.

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
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
end

Then we can use those 2 methods in view.

A single golf clap? Or a long standing ovation?

By clapping more or less, you can signal to us which stories really stand out.