Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using helper in controller in Rails 4.2.4

I'm confused by the rails documentation that I'm reading here. In particular, this sentence:

By default, each controller will include all helpers. These helpers are only accessible on the controller through .helpers

What is this .helpers that it is referring to? I have a helper defined in app/helpers/areas_helper.rb:

module AreasHelper
  def my_helper
    puts "Test from helper"
  end
end

I would like to use this helper in app/controllers/locations_controller.rb:

class LocationsController < ApplicationController
  def show
    helpers.my_helper
  end
end

However, I get a method undefined error. How is this .helpers supposed to be used?

I know there are other ways to get access to helpers in controllers, but I'm specifically asking about this piece of documentation and what it's trying to say.

like image 550
flyingL123 Avatar asked Oct 05 '15 11:10

flyingL123


People also ask

Can we use helper method in controller Rails?

Instead of including the helper module inside the controller you can use the ActionController::Base. helpers available inside your action to have access to every helper method you use inside your views! If you use the include approach in newer Rails applications I strongly suggest you to replace all the includes.

Can we call controller method in Helper?

You generally don't call controller-methods from helpers. That is: if you mean a method that collects data and then renders a view (any other method that needs to be called should probably not be in a controller). It is definitely bad practice and breaks MVC.


2 Answers

This feature was introduced in Rails 5 with following PR https://github.com/rails/rails/pull/24866

So, we can use this feature from Rails 5 and onwards and not in Rails 4.x.

like image 75
Abhishek Jain Avatar answered Sep 28 '22 05:09

Abhishek Jain


You're meant to include the helper class in the controller:

#app/controllers/locations_controller.rb
class LocationsController < ApplicationController
   include AreasHelper

   def show
      my_helper
   end
end
like image 29
Richard Peck Avatar answered Sep 28 '22 05:09

Richard Peck