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:
begin
@cart = Cart.find(the_user_id)
#more code here
rescue ActiveRecord::RecordNotFound
#the cart is empty message
end
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?
Use find_by_id instead of find:
@cart = Cart.find_by_id(params[:id])
nil's if it does not exist so you can check "if @cart" in your controller/view as needed
You could try asking the user object for its cart. Let's say you have the user assigned to @user
then if the user has a cart it would be @user.cart
. If @user.cart
is nil
then they don't have one.
This assumes that you have the relationships between the models set up correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With