I’m using devise and trying to force the user to sign in.
after he signed in, I want to check if his email is found in the table of workers. if it exists, redirect him to: /workers, else to /tasksadmins.
I tried:
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
but I got:
undefined method `email' for nil:NilClass
UPDATE
I tried:
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
Okay, sorry… I’ve just noticed you have updated your question
Dynamic finders like .find_by_email returns single object (first matched) or nil otherwise.
But .where() always returns AR::Relation which can be blank* (empty*) and never nil.
*AR::Relation responds to .blank? and .empty? delegating these methods to collection which actually Array. So the code:
will always return false