Error Handling Question

Being somewhat new to both Ruby and Rails, I am unsure about how to
initiate some kind of error handling.

Currently I have a blog-like application where each post is a
photograph. I am working on the “show” method for the PhotoController
and need to tell the application what to do when a photo cannot be
found with the specified id:

class PhotoController < ApplicationController

def show
if params[:id].nil?
#Take the user to the index page of the most recent photo.
@photo = Photo.find_most_recent
else
#Show a photo with a specified id
if @photo = Photo.find(params[:id], :conditions =>
“publishing_time <= now()”)
else
#Attempt to send them to the most recent post with a
flash[:warning]
flash[:warning] = ‘No published photo exists that satisfies
the given parameters.’
redirect_to :action => “show”
end
end
end

I’m sure many of you already realize this isn’t working as hoped for,
so I am hoping you can fill me in on why. The Photo#find_most_recent
is a very basic method which simply returns the most recent photo
posted.

Right now if I go to http://my.web.app/photo/show/2 everything works
fine. (I have posted about 5 test photos.) If I go to
http://my.web.app/photo/show/ everything works fine, as well. The
error occurs when I go to http://my.web.app/photo/show/32432 . I get
the error message: " ActiveRecord::RecordNotFound in
Photo#show"…“Couldn’t find Photo with ID=32432 AND (publishing_time
<= now())” which is exactly what I didn’t want to see! I was hoping
for the index page with a nice formatted error message for the user. I
have tried rescue statements (which I don’t very much understand) to
no avail and other types of if and else structures.

If you could please educate me in what way I should write my
controller so that it will send me to the index page with a
flash[:warning] I would very much appreciate it! I am trying to
figure out how this error handling is best done. I also am stumped
about how I could send an error message if Photo.find_most_recent
doesn’t return any object, meaning no posts have been made. All help
will be sincerely appreciated! Thanks in advance.

On 6/8/06, Michael K. [email protected] wrote:

def show
the given parameters.’
Right now if I go to http://my.web.app/photo/show/2 everything works
If you could please educate me in what way I should write my

Actually, the easiest way to solve your particular problem would be
not the handling of the exception, but rather a trivial change to
prevent that exception from being raised.

Just use Photo.find(:first …) instead of your current “find by ID”.
“find :first” would return nil instead of raising an exception, so it
seems to be exactly what you want especially as it would work as
expected with the rest of the code you pasted.

I would recommend learning about exception handling for when you
actually need it; grab a copy of the PickAxe or dblack’s excelllent
“Ruby for Rails”.