==============================
Rescue and Redirects
There are a lot of times that you’ll find when you perform a query on
your database that no records are found. Some people that are new to
rails might do something like:
if model.find(:all).empty?
… do something else
else
… continue with our program …
end
But, this doesn’t really help you when you have a very extensive
routine. It also doesn’t really handle ActiveRecord returns or even
logging the errors to your logs.
This is where rescue is a great feature that rails has implemented into
it. How do you use it? Here’s an example:
def get_products(product_id)
begin
@products = Product.find(product_id)
rescue ActiveRecord::RecordNotFound
logger.error("#{product_id} in products wasn’t found from
get_products."
redirect_to :action => :index
else
… continue with your routine
end
end
So, what did we do here?
Pretty simple when you look deeply at it. We have a routine that tries
to find a product by a product_id. Rescue occurs if no record is found
from ActiveRecord and a logger error is placed in your log telling you
what occurred, so you can later review and fix (if it needs fixing) the
error. It then redirects your user back to the index (or you can
specify some other redirect (redirect_to root_url OR redirect_to
controllername_path, etc.). If the rescue doesn’t occur, the method
continues on and processes your routine.
By using rescue you don’t have to interfere greatly with your model’s
core methods. Adding too much logic to your model methods might not be
a good thing. There are times when it might be necessary (methods that
involve rake tasks etc. come to mind) but overall, rescue is something
everyone new to rails should learn and implement into their apps.
I hope this helps.
Thanks.