Rails:控制器中包含的模块中的方法在视图中不可用
奇怪的事情 - 我在 lib/
中有身份验证模块,如下所示:
module Authentication
protected
def current_user
User.find(1)
end
end
在 ApplicationController 中,我包含此模块和所有帮助程序,但方法 current_user 在控制器中可用,但在视图中不可用:( 我怎样才能让这个工作?
Strange thing – I have Authentication module in lib/
like this:
module Authentication
protected
def current_user
User.find(1)
end
end
and in ApplicationController I'm including this module and all helpers, but method current_user is available in controllers, but not from views :( How can I make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果该方法是直接在控制器中定义的,则必须通过调用
helper_method :method_name
使其可用于视图。使用模块,您可以执行相同的操作,但有点棘手。
啊,是的,如果你的模块严格来说是一个辅助模块,你可以按照 Lichtamberg 所说的那样做。 但话又说回来,您可以将其命名为
AuthenticationHelper
并将其放入app/helpers
文件夹中。不过,根据我自己使用身份验证代码的经验,您将希望控制器和视图都可以使用它。 因为通常您将在控制器中处理授权。 助手仅供视图使用。 (我相信它们最初是作为复杂 html 结构的简写。)
If the method were defined directly in the controller, you'd have to make it available to views by calling
helper_method :method_name
.With a module, you can do the same, but it's a bit more tricky.
Ah, yes, if your module is meant to be strictly a helper module, you can do as Lichtamberg said. But then again, you could just name it
AuthenticationHelper
and put it in theapp/helpers
folder.Although, by my own experience with authentication code, you will want to have it be available to both the controller and views. Because generally you'll handle authorization in the controller. Helpers are exclusively available to the view. (I believe them to be originally intended as shorthands for complex html constructs.)
声明了它
您是否在 ApplicationController 中
? http://railsapi.com/ doc/rails-v2.3.3.1/classes/ActionController/Helpers/ClassMethods.html#M001904
Did you declare it with
in your ApplicationController?
http://railsapi.com/doc/rails-v2.3.3.1/classes/ActionController/Helpers/ClassMethods.html#M001904