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.
0de83fd56f1af530034ba8efa5490b1b?d=identicon&s=25 John Butler (johnnybutler7)
on 2006-04-12 15: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??
87e41d0d468ad56a3b07d9a6482fd6d5?d=identicon&s=25 Hemant Kumar (gnufied)
on 2006-04-12 15:30
(Received via mailing list)
wrap your code around :

@post = Post.find(params[:id])
if @post
  # do great things
end
Ef3aa7f7e577ea8cd620462724ddf73b?d=identicon&s=25 Rob Biedenharn (Guest)
on 2006-04-19 14: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 Biedenharn		http://agileconsultingllc.com
Rob@AgileConsultingLLC.com
+1 513-295-4739
This topic is locked and can not be replied to.