我正在尝试使用一个gem,它要求我访问通过控制器扩展登录的当前用户。以下是我的ApplicationController,其中包含我认为应该有效的方法:
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方法?
谢谢你的帮忙!
发布于 2012-01-12 05:35:59
这里的问题在于作用域:如果您将当前用户定义为一个实例方法,那么它将可用于控制器的所有实例(在每次url请求时创建),但您试图将其用作类方法。
因此,要将其定义为类方法:
def self.current_user
...
end但是,如果没有请求,它就没有意义,而且它的意义更小,因为类将在生产中变现,并且set_current_tenant_to只在服务器启动时被调用一次。
另外,对不起,我刚刚看到这里没有答案
发布于 2011-12-02 04:00:03
你的帮助者在私有部分--你希望它在私有区块之外
https://stackoverflow.com/questions/8347191
复制相似问题