Search code examples
ruby-on-railshelperapplicationcontroller

"undefined method" when calling helper method from controller in Rails


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

Solution

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