Forum: Ruby on Rails How to handle failed finds.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ddc850a63a423c3ff963bdf3a097652f?d=identicon&s=25 Larry Kelly (ldk2005)
on 2006-04-03 14:56
(Received via mailing list)
What's the best way to handle a find that doesn't find anything?

For example.

Model Foo

@result = Foo.find(:first, :condition => "some condtion string").name

if  the condition is not met Foo.find stops the application with
'unexpected
nil'.

What is the best way to gracefully trap this error and return something
meaningfull to the calling method?

--
Best Regards,
-Larry
"Work, work, work...there is no satisfactory alternative."
            --- E.Taft Benson
821395fe70906c8290df7f18ac4ac6cf?d=identicon&s=25 Rick Olson (Guest)
on 2006-04-03 15:18
(Received via mailing list)
On 4/3/06, Larry Kelly <ldk2005@gmail.com> wrote:
>
> What is the best way to gracefully trap this error and return something
> meaningfull to the calling method?

@result = Foo.find(:first, :condition => "some condtion string")
@result && @result.name # returns the name or nil

Or you can raise an exception:

@result = Foo.find(:first, :condition => "some condtion string")
raise ActiveRecord::RecordNotFound unless @result
@result.name


--
Rick Olson
http://techno-weenie.net
This topic is locked and can not be replied to.