Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - which is preferable PATCH or POST for updates

I'm working on a standard cart for an ecommerce style application. In the cart we have the standard process of allowing a user to update the qty for an item. I understand how to rig this up using the standard post method passing information to an action in my controller. I did not know about the verbs PATCH and PUT.

If I have a custom action like the one below in my controller (which is called via POST) is PATCH using standard actions like "update" considered more secure? I'm still learning more about rails and PATCH and PUT is a little confusing to me.

carts_controller

def update_cart_qty
  @item = Item.find(params[:line_item][:item_id])
  quantity = params[:line_item][:quantity]

  # if qty is a not a number or negative set to 1 
  quantity = '1' if !quantity.match(/^\d+$/)

  if quantity == '0'
    result = current_cart.line_items.where("item_id = ?", params[:line_item][:item_id]).destroy_all
    respond_to do |format|
        format.js {flash.now[:notice] = "Removed \"#{@item.title}\" from your cart."}
        format.html {flash[:error] = "Removed \"#{@item.title}\" from your cart."}
    end
  else
    result = current_cart.add_item_and_update(@item, quantity, branch, current_user, price)
    current_cart.save
    respond_to do |format|
        format.js {flash.now[:notice] = "Qty \"#{quantity}\" of item \"#{@item.title}\" was updated."}  
        format.html {flash[:notice] = "Qty \"#{quantity}\" of item \"#{@item.title}\" was updated."}
    end
  end
end  
like image 760
Bryan.I Avatar asked Jan 07 '16 21:01

Bryan.I


1 Answers

The docs at jsonapi.org have a good discussion about PUT vs PATCH.

Using PUT to partially update a resource (i.e. to change only some of its state) is not allowed by the HTTP specification. Instead, PUT is supposed to completely replace the state of a resource.

[snip HTTP spec blockquote]

The correct method for partial updates, therefore, is PATCH, which is what JSON API uses. And because PATCH can also be used compliantly for full resource replacement, JSON API hasn't needed to define any behavior for PUT so far. However, it may define PUT semantics in the future.

In the past, many APIs used PUT for partial updates because PATCH wasn’t yet well-supported. However, almost all clients now support PATCH, and those that don’t can be easily worked around.

The basic idea is that PUT should only be used when you're completely replacing a resource and PATCH should be used for partial replacement/updates. POST can be used for any non-idempotent operation.

like image 134
drhining Avatar answered Sep 27 '22 21:09

drhining