views:

160

answers:

2

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

+2  A: 

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
Thanks for the fast response! :)
siulamvictor
+1  A: 

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
Dmitry Nesteruk