首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >来自ApplicationController的访问方法

来自ApplicationController的访问方法
EN

Stack Overflow用户
提问于 2011-12-02 03:33:20
回答 2查看 2.1K关注 0票数 0

我正在尝试使用一个gem,它要求我访问通过控制器扩展登录的当前用户。以下是我的ApplicationController,其中包含我认为应该有效的方法:

代码语言:javascript
复制
class ApplicationController < ActionController::Base
  helper :all
  protect_from_forgery
  set_current_tenant_to(current_user.member)

  private

     def current_user
      @current_user ||= User.find(session[:user_id]) if session[:user_id]
     end

     helper_method :current_user

     def require_user
       unless current_user
        flash[:notice] = "You must be logged in to access this page"
        redirect_to '/login'
        return false
       end
     end
end

这在set_current_tenant_to上失败,出现"undefined local variable or method `current_user‘for ApplicationController:Class“。

有没有办法通过控制器扩展访问current_user方法?

谢谢你的帮忙!

EN

回答 2

Stack Overflow用户

发布于 2012-01-12 05:35:59

这里的问题在于作用域:如果您将当前用户定义为一个实例方法,那么它将可用于控制器的所有实例(在每次url请求时创建),但您试图将其用作类方法。

因此,要将其定义为类方法:

代码语言:javascript
复制
def self.current_user
  ...
end

但是,如果没有请求,它就没有意义,而且它的意义更小,因为类将在生产中变现,并且set_current_tenant_to只在服务器启动时被调用一次。

另外,对不起,我刚刚看到这里没有答案

票数 3
EN

Stack Overflow用户

发布于 2011-12-02 04:00:03

你的帮助者在私有部分--你希望它在私有区块之外

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8347191

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档