10
votes

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.

2
I believe the reference to .helpers is the inbuilt Rails helpers, such as redirect_to etcRichard Peck
But what does that mean. Where does .helpers come into play when using a built in Rails helper like redirect_to?flyingL123
Tbh I don't know. I am reading up on it. My answer is valid, that's how we use custom helpers in our controllers - as for .helpers I am looking at itRichard Peck
Thanks. I am looking for an answer or explanation specifically for that part of the documentation if possible.flyingL123
As far as I understood Helpers are often used in your VIEW. Eg, having your own complex 'link_to' version. This way you can still keep complex logic out of the view and just call the method from it.Philipp Meissner

2 Answers

9
votes

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
5
votes

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.