What is the recommended way of handling the following type of situations:
Supposing I have a model called Cart, that has a 1-1 relationship with the model Person and the same PK (the user's id).
In the index method of my cart_controller I want to check if a Cart exists for the current user.
If I do Cart.find(the_user_id) and a cart doesn't exists a RecordNotFound exception gets raised.
I see two ways of solving this:
1. rescue from the exception
begin
@cart = Cart.find(the_user_id)
#more code here
rescue ActiveRecord::RecordNotFound
#the cart is empty message
end
2. use ActiveRecord#exists? method
if Cart.exists?(the_user_id)
@cart = Cart.find(the_user_id)
#more code here
else
#the cart is empty message
end
From my (limited) knowledge on exeption handling I know that it's not recommended to use exceptions this way, but is making an extra query every time worth it?