-1

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

Fassbender
  • 121
  • 8

3 Answers3

0
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

hitesh israni
  • 1,742
  • 4
  • 25
  • 48
  • This code doesn't work. I still have de exception : ActiveRecord::RecordNotFound in TasksController#index - Couldn't find User with id=14. I don't know how handling this exception.. – Fassbender Mar 31 '12 at 17:18
  • if you are using User.find in index action of TasksController then use User.find_by_id(session[:user_id]) as shown above. – hitesh israni Mar 31 '12 at 17:40
  • Did you know why find_by_id not handling exception RecordNotFound ? – Fassbender Mar 31 '12 at 20:25
  • find_by_id silently returns nil. it doesnot raises an exception when a record is not found, as find do. – hitesh israni Mar 31 '12 at 20:34
0

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
Nilesh
  • 1,149
  • 9
  • 14
  • In SQL select * from users where id = 15 return nothing. And with my code ActiveRecord::RecordNotFound in TasksController#index - Couldn't find User with id=14. Thx for the nil tips. – Fassbender Mar 31 '12 at 17:15
  • so what is in your TasksController#index can you provide that code. – Nilesh Mar 31 '12 at 17:28
0

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
Harish Shetty
  • 64,083
  • 21
  • 152
  • 198