Does anyone know why I get
undefined method `my_method' for #<MyController:0x1043a7410>
when I call my_method("string") from within my ApplicationController subclass? My controller looks like
class MyController < ApplicationController def show @value = my_method(params[:string]) end end
and my helper
module ApplicationHelper def my_method(string) return string end end
and finally, ApplicationController
class ApplicationController < ActionController::Base after_filter :set_content_type helper :all helper_method :current_user_session, :current_user filter_parameter_logging :password protect_from_forgery # See ActionController::RequestForgeryProtection for details
In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.
A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words .
You cannot call helpers from controllers. Your best bet is to create the method in ApplicationController
if it needs to be used in multiple controllers.
EDIT: to be clear, I think a lot of the confusion (correct me if I'm wrong) stems from the helper :all
call. helper :all
really just includes all of your helpers for use under any controller on the view side. In much earlier versions of Rails, the namespacing of the helpers determined which controllers' views could use the helpers.
I hope this helps.
view_context is your friend, http://apidock.com/rails/AbstractController/Rendering/view_context
if you wanna share methods between controller and view you have further options:
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