I’m working through Agile Web Development with Rails
In part E3, it says to replace the following method:
def destroy
@cart = Cart.find(params[:id])
@cart.destroy
with
def destroy
@cart = current_cart
@cart.destroy
where
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
My question is, what is the advantage of using the second method over the first? I can’t see any circumstance where the second would fail? This is calling the method from:
<%= button_to 'Delete Cart', method: :destroy %>
From within the cart view. Doesn’t it implicitly always pass in the correct cart_id?? Or is this modification for destroy for future uses, for example when we are trying to delete the cart from another view? If this latter explanation is correct, do we need to always store id’s in the :session hash?
Thanks for your help.
For starters, it offers a some protection against someone maliciously modifying the url and
passing &cart_id=ID_TO_CART_I_DONT_OWN. See https://www.owasp.org/index.php/Top_10_2010-A4.You’re also saving yourself a database lookup by getting the cart from the session [although rails is pretty good with db caching by default]. About it possibly failing, what happens if the record no longer exists by the time you hit the “Delete Cart” button ?
Cart.find(params[:id])will raise an exception that you’re not handling, the second method will handle the exception and fail quietly; this is not necessarily always a good thing.