【问题标题】:What do these parameters mean in the respond_to block?这些参数在 respond_to 块中是什么意思?
【发布时间】:2016-04-30 06:03:25
【问题描述】:

我是 Rails 新手,对下面代码中的 format.json 行感到困惑。 status: :createdlocation: @product 指的是什么?

def create
      @product = Product.new(params[:product])

  respond_to do |format|
    if @product.save
      format.html { redirect_to @product, notice: 'Product was successfully created.' }
      format.json { render json: @product, status: :created, location: @product }
      format.js
    else
      format.html { render action: "new" }
      format.json { render json: @product.errors, status: :unprocessable_entity }
      format.js
    end
  end
end

包括状态和位置是可选的吗?我对什么是可选的以及为什么要添加自定义状态/位置感到困惑。

【问题讨论】:

标签: ruby-on-rails json model-view-controller


【解决方案1】:
  • status: :created 表示 Rails 应用程序响应的 HTTP 状态 - 整数表示形式为 201。 List of HTTP statuses here
  • location: @product 实际上会生成 url 来显示 ProductsController 的操作,如 product_path(@product) 并设置响应的 HTTP 位置标头。意味着可以使用 HTTP GET 请求在给定位置 URL 上检索资源,更多信息 here

【讨论】:

  • 添加状态和位置是可选的吗?为什么?谢谢
  • 这是可选的,但正确的状态和位置是 HTTP 规范的一部分。遵循它们并尽可能保持应用程序的标准总是好的。例如,此 JSON API 可能被客户端 JS 应用程序或移动应用程序使用。对于开发人员来说,使用标准界面而不是自定义界面会更容易。牢记 Ruby 的主要原则——“减少意外行为”:)
【解决方案2】:

如果很容易的话。

您可以发送不同的请求格式 - html(默认)、jsonjs

默认action等待html请求,如果得到,action会混淆,例如json。因此,为了避免这种情况,您必须添加 format.json {} 并在大括号中添加您想要呈现的信息。

编辑

更多详情可以READ HEAR

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 2014-12-24
    • 2020-09-25
    相关资源
    最近更新 更多