views:

986

answers:

3

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
+1  A: 

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). Before, the namespacing of the helpers determined which controllers' views could use the helpers.

I hope this helps.

theIV
Good information. I actually ended creating a module for my method, as promoted in the following thread, since the method is pretty generic (it converts a string to be url safe) and shouldn't be specific to controllers: http://stackoverflow.com/questions/128450/best-practices-for-reusing-code-between-controllers-in-ruby-on-rails/130821#130821
Chad Johnson
+1  A: 

Maybe I'm wrong, but aren't the helpers just for views? Usually if you need a function in a controller, you put it into ApplicationController as every function there is available in its childclasses.

stex
Hm, that sucks. I wish I could use methods in both controllers and views. Oh well.
Chad Johnson
You can, kind of... Your `helper_method` call is giving you access to those methods in your views.
theIV
+1  A: 

As far as i know, helper :all makes the helpers available in the views...

j.