gpt4 book ai didi

ruby-on-rails - rails : methods from module included in controller not available in view

转载 作者:行者123 更新时间:2023-12-03 07:47:31 26 4
gpt4 key购买 nike

奇怪的事情 - 我在 lib/ 中有身份验证模块,如下所示:

module Authentication
protected

def current_user
User.find(1)
end

end

在 ApplicationController 中,我包含此模块和所有帮助程序,但方法 current_user 在 Controller 中可用,但在 View 中不可用:(我怎样才能使其工作?

最佳答案

如果该方法是直接在 Controller 中定义的,则必须通过调用 helper_method :method_name 使其可用于 View 。

class ApplicationController < ActionController::Base

def current_user
# ...
end

helper_method :current_user
end

使用模块,您可以执行相同的操作,但有点棘手。

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

啊,是的,如果你的模块严格来说是一个辅助模块,你可以按照 Lichtamberg 所说的那样做。但话又说回来,您可以将其命名为 AuthenticationHelper 并将其放入 app/helpers 文件夹中。

不过,根据我自己使用身份验证代码的经验,您希望它可用于 Controller 和 View 。因为通常您将在 Controller 中处理授权。助手仅供 View 使用。 (我相信它们最初是作为复杂 html 结构的简写。)

关于ruby-on-rails - rails : methods from module included in controller not available in view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1265323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com