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.
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.
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.
On Jan 11, 2008 12:22 AM, Theo Graham-brown [email protected] wrote:
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.
Pick up a copy of Obie’s book, The Rails Way. It’s all about
documenting the Rails way of doing things.
Pat
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.