3

I created a helper method for some simple calculation. This helper method will just return an integer. I need the helper in both controllers and views.

Unfortunately, it work well in views but not in controllers. I get the undefined local variable or method error. How can I fix it?

Thanks all

tstyle
  • 748
  • 1
  • 10
  • 23
Victor Lam
  • 3,646
  • 8
  • 31
  • 43

2 Answers2

10

In order to use same methods in both controller and views Add you method in application_controller.rb and make it helper methods.

For example

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  #protect_from_forgery # See ActionController::RequestForgeryProtection for details
  helper_method :current_user 

  def current_user
    session[:user]
  end

end

Now you can use method current_user in both controllers & views

Salil
  • 46,566
  • 21
  • 122
  • 156
  • Thanks for the fast response! :) – Victor Lam May 13 '10 at 10:56
  • A note about this example: since `helper :all` defines all public methods as helpers, there is no need for both `helper :all` and `helper_method :current_user`. It's an either/or proposition. – Pierre Oct 01 '12 at 14:59
4

I use a following solution. Because I think helper's methods shoud be stored in an appropriate helper module.

module TestHelper
  def my_helper_method
    #something
  end
end


class SomeController < ApplicationController
  def index
    template.my_helper_method
  end
end
Dmytro Nesteriuk
  • 8,315
  • 1
  • 18
  • 14
  • I prefer this solution to the chosen one. But, minor change with the latest rails: SO http://stackoverflow.com/questions/3300582/rails-3-template-variable-inside-controllers-is-nil you need to use view_context instead of @template. – saudai Mar 20 '14 at 13:25