ruby-on-rails - Rails 4 - 最好使用 PATCH 或 POST 进行更新

标签 ruby-on-rails ruby-on-rails-4 post

我正在为电子商务风格的应用程序开发一个标准的购物车。在购物车中,我们有允许用户更新商品数量的标准流程。我了解如何使用标准的 post 方法将信息传递给我的 Controller 中的一个 Action 来装配它。我不知道动词 补丁 .

如果我的 Controller 中有一个像下面这样的自定义操作(通过 POST 调用),使用“更新”等标准操作的 PATCH 被认为更安全吗?
我仍在学习更多关于 rails 和 PATCH 的知识,而 PUT 对我来说有点困惑。

购物车 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  

最佳答案

jsonapi.org 上的文档对 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.


基本思想是,只有在完全替换资源时才应使用 PUT,而应将 PATCH 用于部分替换/更新。 POST 可用于任何非幂等操作。

关于ruby-on-rails - Rails 4 - 最好使用 PATCH 或 POST 进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34665655/

相关文章:

ruby-on-rails - Rails App 在后台运行长时间任务的最佳实践?

Jquery Autocomplete Gem-将参数传递到数据库

ruby-on-rails - 通过脚手架生成的 Controller 上的空(但有效)显示方法?

ruby-on-rails - 验证 Rails 4 中的电话号码格式 - REGEX

php - 我的登录 PHP 脚本出现故障

ruby-on-rails - 从命令行启动时阻止 sidekiq 执行排队的作业?

ruby-on-rails - 使用 ActiveModel::Validations 验证嵌套模型

ruby-on-rails - 如何阻止路由错误错误导致各种警告?

java - 将非拉丁数据从 Java 发送到 PHP

angularjs - 使用 AngularJS 将字符串数据发布到 Web API 结果为 null