0

我正在使用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
4

3 回答 3

1

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

于 2012-12-29T18:44:14.157 回答
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 ,它可以是空白* (empty*) 并且永远不会是 nil

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

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

将始终返回false

于 2012-12-29T18:55:44.907 回答
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
于 2012-12-29T18:59:08.337 回答