Handle null item

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??

wrap your code around :

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

do great things

end

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
[email protected]
+1 513-295-4739