Dynamic Finders don't give Exceptions? Or I can't get any...

Hi,

This has been bugging me a bit.

If I do the code:

begin
  user = User.find(:id)
rescue
  flash[:notice] = "Invalid ID"
else
  # rest of code
end

It works fine catching an invalid ID. However this code:

begin
  user = User.find_by_email(:email)
rescue
  flash[:notice] = "Invalid Email"
else
  # rest of code
end

Never raises an exception and I have to check if 'user == nil'. This is
irritating because it means my code has to be structured differently in
each case. Am I doing something wrong? I'd like to have one style of
error checking after every database read, for clarity.

Cheers
Theo

There's a sidebar in AWDWR that discusses that. The gist is that if
you do User.find(1), then you expect that record to exist. If you do
User.find_by_some_attribute("foo"), then it's more of a scan, and not
finding a result isn't exceptional.

You can use User.find_by_id(1) if you want those same no-error
semantics. I think it's best to use whichever expresses your intent
better, rather than simply trying for uniformity.

Pat

Pat Maddox wrote:

  flash[:notice] = "Invalid ID"
else
--
Posted via http://www.ruby-forum.com/.

>

There's a sidebar in AWDWR that discusses that. The gist is that if
you do User.find(1), then you expect that record to exist. If you do
User.find_by_some_attribute("foo"), then it's more of a scan, and not
finding a result isn't exceptional.

You can use User.find_by_id(1) if you want those same no-error
semantics. I think it's best to use whichever expresses your intent
better, rather than simply trying for uniformity.

Pat

Okay, that makes sense. I'll leave it as it is, then. I worry that I am
a very poor Rails programmer, you see.

With PHP/C#/C++/C/Java stuff it's so well documentated that you can
quickly see when you're writing in a clear and correct style, but I just
don't know enough about Rails to know if I'm making a mess of things.

Cheers
Theo

Pick up a copy of Obie's book, The Rails Way. It's all about
documenting the Rails way of doing things.

Pat