Reputation: 7121
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
Upvotes: 0
Views: 1010
Reputation: 4496
Okay, sorry... I've just noticed you have updated your question
#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
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:
tag = Worker.where(:email => @email)
if tag.nil?
will always return false
Upvotes: 1
Reputation: 4053
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
Upvotes: 1
Reputation: 480
If the user does not authenticate successfully, cuurent_user would be nil. Am I correct in assuming that you are using devise for authentication?
Upvotes: 1