Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 通过rails中的助手方法访问用户属性_Ruby On Rails_Ruby_Session_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 通过rails中的助手方法访问用户属性

Ruby on rails 通过rails中的助手方法访问用户属性,ruby-on-rails,ruby,session,ruby-on-rails-4,Ruby On Rails,Ruby,Session,Ruby On Rails 4,我写了这个助手方法: class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception private def current_user @

我写了这个助手方法:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  private

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
  helper_method :current_user
end
class ApplicationController
在我看来,我应该能够这样做
current_user.role==“some role”
,但是当我这样做的时候,它突然冒出来说“nil:NilClass的未定义方法角色”,现在这是否意味着role列是空的,里面没有任何内容,或者user对象是空的?因为我向你保证我已登录,我存在于数据库中,并且。。。。数据库中的角色字段始终为空


Update我可能应该声明doing
User.role==“admin”
有效,因为它们是数据库或well列中的角色属性。为什么我不能对当前用户执行.role操作?

基于此错误,可以确定当前用户返回的值为nil。所以问题不在于方法角色。应该注意,User.role是模型用户上的一个类方法,因此它不会对一个特定用户调用方法。另一方面,current_user.role是一个特定用户(即已登录的用户)的实例方法

我将在抛出错误的方法上方放置以下内容:

raise session[:user_id].inspect
在使用上述方法确认会话cookie中存在适当的用户\u id之后,您还可以在当前\u用户帮助器方法的末尾添加以下内容,以确认实际返回了用户:

raise @current_user.inspect 

您用于创建会话[:user\u id]的逻辑是什么?此外,您可能需要清除浏览器缓存或打开一个匿名窗口(在chrome中为cmd+shift+n),然后返回应用程序的登录过程。

该消息意味着
当前用户
正在返回
nil
。您如何处理登录?