There are times that you want to access a method in helpers from controller in ruby on rails. Or you may want to access method in controller from a helper class. This article explains how you might want to share code between controller and helpers class in ruby on rails. However, you should try to avoid mix codes in helpers and controllers. The reason is that helpers are meant to be used in views to help in format the layout or display data and controllers are meant to control the whole application.

If there are many methods or variables that you want to share between controllers and helpers. You may want to create a module and put it under lib directory. Then you can include the module in controller or helpers class. In this way, both the controller and helper class should be able to access the methods. However, do note that when you require a module in a class, if you later changes anything in that module, the changes won’t take effect for the class that includes the module until you restart your ruby on rails server.

Usually, you will see the following code in the application controller.

helper :all

This line doesn’t mean that the controller can access all the methods in helper but means that all the views are able to access all the helpers class. Don’t just take the meaning of the words. If you don’t want to create a module but just want share a method between controller and helpers the following is the best way that I know.

If you just want to access a certain method in a controller say application controller from a helper class say application_helper. You might do the following to access the method in the controller.

def check_access
    return @controller.has_access_right?
end

The has_access_right? is a method in application controller. If you directly access this method in application helper, you will get a No Method Error.

On the other hand, if you just want to access a certain method in a helper. You might want to do the following to access the method in the helper:

class ApplicationController < ActionController::Base
  def  check_number number_
    result = @template.double(number_)
    return result > 20
  end
end

Of course, the method is just a rubbish method to demo how you might access a method in a helper from a controller.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

HTML tags are not allowed.