Reputation: 3
can somebody help me out here. With the conditional statement below, only the first and second conditions are ever met, the third (second elsif statement) and last are never met. I've tried moving use case statement, but I get the same result.
def current_user
if Stylist.exists?(session[:user_id]) && Stylist.find(session[:user_id]).has_role?(:def_stylist)
@current_user = Stylist.find(session[:user_id])
elsif Client.exists?(session[:user_id]) && Client.find(session[:user_id]).has_role?(:def_client)
@current_user = Client.find(session[:user_id])
elsif Admin.exists?(session[:user_id]) && Admin.find(session[:user_id]).has_role?(:def_admin)
@current_user = Admin.find(session[:user_id])
else
@current_user = nil
end
end
Upvotes: 0
Views: 103
Reputation: 1484
Last condition will be met only when we are not able to find Stylist, Client or Admin.
I thing the issue is with the coditions, Suppose your admin user id is 1 and 1 is the client id as well who has def_client role,
So when admin login then we check for id 1 to be present in Client
table and finds the client. You should set diffent session for different roles.
I think after changing session keys this will work.
def current_user
@current_user =
if session[:stylist_user_id] && Stylist.find(session[:stylist_user_id]).has_role?(:def_stylist)
Stylist.find(session[:stylist_user_id])
elsif Client.exists?(session[:client_user_id]) && Client.find(session[:client_user_id]).has_role?(:def_client)
Client.find(session[:client_user_id])
elsif Admin.exists?(session[:admin_user_id]) && Admin.find(session[:admin_user_id]).has_role?(:def_admin)
Admin.find(session[:admin_user_id])
end
end
Update : You can further reduce the queries by changing your code. Bear in mind that exist triggers a query then you check for roles which again creates a query on Stylist, client or admin then we have find query which we can reduce by changing code to something like below.
def current_user
@current_user =
if session[:stylist_user_id]
stylist = Stylist.find(session[:stylist_user_id])
stylist if stylist.has_role?(:def_stylist)
elsif session[:client_user_id]
client = Client.find(session[:client_user_id])
client if client.has_role?(:def_client)
elsif session[:admin_user_id]
admin = Admin.find(session[:admin_user_id])
admin if admin.has_role?(:def_admin)
end
end
Upvotes: 1