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?
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.
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