3

我为一些简单的计算创建了一个辅助方法。这个辅助方法只会返回一个整数。我需要控制器和视图中的助手。

不幸的是,它在视图中运行良好,但在控制器中却不行。我得到了undefined local variable or method错误。我该如何解决?

谢谢大家

4

2 回答 2

10

为了在控制器和视图中使用相同的方法,在 application_controller.rb 中添加你的方法并使其成为辅助方法

例如

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

现在您可以在控制器和视图中使用方法current_user

于 2010-05-13T10:54:14.163 回答
4

我使用以下解决方案。因为我认为助手的方法应该存储在适当的助手模块中。

module TestHelper
  def my_helper_method
    #something
  end
end


class SomeController < ApplicationController
  def index
    template.my_helper_method
  end
end
于 2010-05-13T15:12:24.983 回答