rails:控制器中包含的模块的方法在视图中不可用

Ale*_*sev 11 namespaces ruby-on-rails helpers

奇怪的是 - 我有这样的身份验证模块lib/:

module Authentication
  protected

  def current_user
    User.find(1)
  end

end
Run Code Online (Sandbox Code Playgroud)

在ApplicationController中,我包含了这个模块和所有帮助程序,但方法current_user在控制器中可用,但不在视图中:(如何使其工作?

kch*_*kch 30

如果方法是直接在控制器中定义的,则必须通过调用使其可用于视图helper_method :method_name.

class ApplicationController < ActionController::Base

  def current_user
    # ...
  end

  helper_method :current_user
end
Run Code Online (Sandbox Code Playgroud)

使用模块,您也可以这样做,但它有点棘手.

module Authentication
  def current_user
    # ...
  end

  def self.included m
    return unless m < ActionController::Base
    m.helper_method :current_user # , :any_other_helper_methods
  end
end

class ApplicationController < ActionController::Base
  include Authentication
end
Run Code Online (Sandbox Code Playgroud)

啊,是的,如果你的模块是严格意义上的帮助模块,你可以像Lichtamberg所说的那样做.但话说回来,您可以AuthenticationHelper将其命名并将其放入app/helpers文件夹中.

虽然,根据我自己的身份验证代码经验,您可能希望控制器和视图都可以使用它.因为通常你会在控制器中处理授权.帮助者可以独家观看.(我相信它们最初是作为复杂html构造的缩写.)

  • 我在 m.helper_method 上有未定义的方法 `helper_method' #&lt;Class:0xb139e5c&gt; :current_user :((( (2认同)