1

I'm wondering what is best practive for handling this type of situation in ruby on rails.

users_controller.rb

def show
  @user = User.find params[:id]
end

If user is not found it throws an exception which isn't catched anywhere so it will display some ugly things to enduser.

Solution would be pack it into begin...rescue...end block:

def show
  begin
    @user = User.find params[:id]
  rescue
    flash[:error] = "User not found"
    redirect :action => :index
  end
end

although I've never seen such code in any rails article or tutorial I've seen.

What is the proper way of handling this type of situations?

Adrian Serafin
  • 7,665
  • 5
  • 46
  • 67

5 Answers5

3

See docs rescue_from

egze
  • 3,200
  • 23
  • 23
2

It depends on your requirement. But you want a general solution then you can have a rescue block in ApplicaionController which will handle the RecordNotFound exception.

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
Ashish
  • 5,723
  • 2
  • 24
  • 25
1

You can do

def show
  @user = User.find_by_id(params[:id])
  unless @user
    flash[:error] = "User not found"
    redirect :action => :index
  end
end

But you cant expect you will call a link with id which is not in the db from within the application. Please see the answer of the question

Community
  • 1
  • 1
rubyprince
  • 17,559
  • 11
  • 64
  • 104
  • thank's for the link, but I think I can expect wrong id because input comes from user and he can mess with url and I want some friendly message telling that what he was looking for doesn't exisit. – Adrian Serafin Mar 04 '11 at 13:38
1

The development environment will show you ugly error messages, but a production environment will just give an HTTP 404 error (page not found) when the id is invalid.

Thomas Andrews
  • 1,577
  • 1
  • 13
  • 31
0

I think that you may be able to fix this with @user = User.find(params[:id] = current_user)

Jake Cooper
  • 121
  • 7