3

I have a custom helper in app/helpers/posts_helpers.rb:

module PostsHelper
  def custom_helper(post)
    #do something
  end
end

When I call this from one of views, I get the error:

ActionView::Template::Error (undefined method 'custom_helper' for class..

But if I call the same helper from app/helpers/application_helper.rb as follows, then the view is able to detect the helper.

module ApplicationHelper
  def custom_helper(post)
    #do something
  end
end

Even tried setting the include all helper option to true explicitly although it is true by default in config/application.rb. That didn't help either.

config.action_controller.include_all_helpers = true

Why didn't it work?

ekremkaraca
  • 1,453
  • 2
  • 18
  • 37
varneohas
  • 71
  • 4

1 Answers1

1

By default, methods in helpers are available only to their corresponding controllers. For example, PostsController has access to methods in the PostsHelper, but the various posts views don't. If you want to make those methods available to the views, designate them as helper_methods, like so:

module PostsHelper

  helper_method :custom_helper

  def custom_helper(post)
    #do something
 end
end

In contrast, methods defined in ApplicationHelper are available globally, i.e. in all controllers and views.

You can read the excellent answer provided here for more detail.

You can also include a module in ApplicationHelper to give its methods global accessibility:

module ApplicationHelper

  include PostsHelper
  ...

end

That's not always a good idea though, because it can make your code difficult to understand and maintain later.

Community
  • 1
  • 1
Ege Ersoz
  • 6,461
  • 8
  • 34
  • 53
  • Thanks for responding. helper_method is for methods under controller. The ones I am asking about here are, from the app/helpers/ folder. These are not available to controllers but available to views by default. – varneohas May 26 '14 at 21:34