ActiveRecord#exists? or rescue from ActiveRecord::RecordNotFound
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.
Why don't you do something like...
@cart = @user.cart || @user.cart.new
No worrying about exceptions or if/else statements.Then in your view you could have something like...
<% if @cart.empty? # or whatever method you use to determine # if there is nothing in the cart...maybe .blank? is fine? %> <p>Your cart is empty</p><% else %> <!-- loop through objects in your cart --><% end %>