Ruby Exception - If Statement rescue doesn't handling exception
-
28-05-2021 - |
Question
I everyone, I've some issue to handling exception in ruby. I doesn't understand why my statement doesn't work.
Error : Couldn't find User with id=14 I want to redirect to the login page.
def login_required
begin
if session[:user_id] == nil
redirect_to login_path, :notice => "You are not logged"
elsif User.find(session[:user_id])
return nil
end
rescue ActiveRecord::RecordNotFound
redirect_to login_path, :notice => "No user corresponding in database"
end
end
Hope you can help me.
Cordially, Aubin
Solution
def login_required
begin
if session[:user_id] == nil
redirect_to login_path, :notice => "You are not logged"
elsif User.find_by_id(session[:user_id]).nil?
#rescue ActiveRecord::RecordNotFound (use if u want to use User.find)
redirect_to login_path, :notice => "No user corresponding in database"
return nil
end
end
end
OTHER TIPS
The only reason for this to not work is that ActiveRecord is actually finding a row
User.find(session[:user_id])
Try logging the session[:user_id] and looking into DB using SQL.
On another note, you can use
session[:user_id].nil?
instead of
session[:user_id] == nil
I would rewrite your method as follows:
def login_required
return redirect_to(login_path,
:notice => "You are not logged") if session[:user_id].blank?
user = User.find_by_id(session[:user_id])
return user if user.present?
redirect_to login_path, :notice => "No user corresponding in database"
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow