未定义的方法`email'代表nil:NilClass

时间:2012-12-29 18:25:39

标签: ruby-on-rails devise

我正在使用devise并尝试强制用户登录。 在他登录后,我想检查他的电子邮件是否在工人表中找到。如果存在,请将其重定向到:/workers,否则转到/tasksadmins

我试过了:

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :authenticate_user!
  before_filter :is_worker

  def is_worker

     @email = current_user.email
     tag = Worker.where(:email => @email)
     if tag.nil?
        redirect_to '/tasksadmins'
     else
        redirect_to '/workers'
     end
  end
end

但我得到了:

undefined method `email' for nil:NilClass

更新

我试过了:

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :authenticate_user!
  before_filter :is_worker

  def is_worker
    if user_signed_in?
       @email = current_user.try(:email)
      if @email && Worker.find_by_email(@email).nil?
        redirect_to '/tasksadmins'
      else
        redirect_to '/workers'
      end
    else
        redirect_to '/users/sign_in' # devise?
    end
  end
end

3 个答案:

答案 0 :(得分:1)

如果用户未成功进行身份验证,则cuurent_user将为nil。假设您使用设计进行身份验证,我是否正确?

答案 1 :(得分:1)

好的,对不起......我刚刚注意到你已经更新了你的问题

#SessionsController

def after_sign_in_path_for(resource)
  return request.env['omniauth.origin'] || session[:user_return_to] || root_path
end


#Your controller

before_filter :user_return_to
before_filter :authenticate_user!
before_filter :is_worker

def is_worker
   @email = current_user.try(:email)
   if @email && Worker.find_by_email(@email).nil?
      redirect_to '/tasksadmins'
   else
      redirect_to '/workers'
   end
end

private

def user_return_to
  session[:user_return_to] = request.fullpath
end

.find_by_email 等动态查找器会返回单个对象(首先匹配)或 nil

.where()始终返回AR :: Relation,可以为空*(空*)和永不为

* AR :: Relation响应.blank?和.empty?将这些方法委托给实际上是Array的集合。所以代码:

tag = Worker.where(:email => @email)
if tag.nil?

将始终返回 false

答案 2 :(得分:1)

 def is_worker
     render :template => '/login' and return if current_user.nil?
     @email = current_user.email
     tag = Worker.where(:email => @email)
     if tag.nil?
        redirect_to '/tasksadmins'
     else
        redirect_to '/workers'
     end
  end