Alex Rivera | Logout

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

Asked 2010-03-05T18:11:18.313
45

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
Edit
Report

1 Answer

0

I had the same problem...

you can hack/bodge around it, put that logic into a model, or make a class specially for it. Models are accessible to controllers, unlike those pesky helper methods.

Here is my "rag.rb" model

class Rag < ActiveRecord::Base
  belongs_to :report
  def miaow()
    cat = "catattack"
  end  
end

Here is part of my "rags_controller.rb" controller

def update
  @rag = Rag.find(params[:id])
  puts @rag.miaow()
  ...

This gave a catattack on the terminal, after I clicked "update".

Given an instantiation, methods in the model can be called. Replace catattack with some codes. (This is the best I have so far)

:helper all only opens helpers up to views.

This shows how to make a class and call it. http://railscasts.com/episodes/101-refactoring-out-helper-object?autoplay=true

answered 2011-07-28T16:58:09.770

Your Answer