Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Since you are dealing with real time application like Shopping Cart, there is a great chance that two or more users access the application at the same time and buy the same product. Although the params[:id] is unique for each user but any user can maliciously enter into other with a hack and this will cause a serious drawback.

Having so, Your application has a session for each user in which you can store small amounts of data that will be persisted between requests for that user. Managing sessions for each user maintains the consistency and there is a nice resource management. This will not create any havoc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top