Search code examples
ruby-on-railsrubyexceptionrescue

Ruby Exception - If Statement rescue doesn't handling exception


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