How do I set up a method that I want accessible from all controllers?
Sticking the method in application_helper just makes it available to the views
In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.
A Helper method is used to perform a particular repetitive task common across multiple classes. This keeps us from repeating the same piece of code in different classes again and again. And then in the view code, you call the helper method and pass it to the user as an argument.
If you need to use a method in the application scope then I would suggest that you keep those methods inside the application controller and in order to use them inside views.. declare those as helper methods. The problem is that if there are many helper methods, ApplicationController can become unwieldy.
You can add the method to ApplicationController
. All the other controllers subclass ApplicationController
, so will be able to call the method.
You'll want to make the method protected
so that it is only visible to subclasses and isn't available as a web-accessible action.
You can include ApplicationHelper
in your controllers (or base ApplicationController) to make the helper methods available.
You can also include the following line in your ApplicationController to include all helpers:
helper :all
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With