Forum: Ruby on Rails Handle null item

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.
John B. (Guest)
on 2006-04-12 17:24
Hi,

How to i handle a find that returns a null?

Say i put 40 into the paramter id below and there is no post with an id
of 40
i get an error saying no post exists with id

@post = Post.find(params[:id])

Anyone help??
Hemant K. (Guest)
on 2006-04-12 17:30
(Received via mailing list)
wrap your code around :

@post = Post.find(params[:id])
if @post
  # do great things
end
Rob B. (Guest)
on 2006-04-19 16:39
(Received via mailing list)
That won't work either.  Try one of these:

begin
   @post = Post.find(params[:id])
   # use the @post that was found
rescue
   # do something about a non-existant record
end

#-OR-

if @post = Post.find_by_id(params[:id])
   # use the @post that was found
else
   # do something about a non-existant record
end

The dynamic finders (find_by_id in this case) return nil, but find
raises an exception.

-Rob

Rob B.		http://agileconsultingllc.com
removed_email_address@domain.invalid
+1 513-295-4739
This topic is locked and can not be replied to.