2016-01-23 61 views
-1

我是新来的铁轨,并且对以下代码中的format.json行感到困惑。 status: :createdlocation: @product指的是什么?这些参数在respond_to块中的含义是什么?

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 

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

+2

的[什么\'可能重复:位置=> ... \'和\'头:OK \'指的是在“回应\ _to'format statement?](http://stackoverflow.com/questions/5213956/what-does-location-and-head-ok-mean-in-the-respond-to-format-stat) –

回答

0
  • status: :created表示Rails应用程序响应的HTTP状态 - 整数表示为201。 List of HTTP statuses here
  • location: @product实际上会生成url来显示ProductsController的动作,如product_path(@product),并设置响应的HTTP位置标题。意味着可以通过HTTP GET请求在给定位置URL上检索资源,更多信息here
+0

正在添加状态和位置可选?为什么?谢谢 –

+0

这是可选的,但正确的状态和位置是HTTP规范的一部分。遵守它们并尽可能保持应用程序的标准总是很好的。例如,这个JSON API可以被客户端JS应用程序或移动应用程序使用。对于开发人员来说,使用标准界面而不是自定义工作会更容易。请记住主要的Ruby原则 - “减少惊喜行为”:) – Semjon

0

如果非常容易。

您可以发送差异要求的格式 - html(默认),jsonjs

默认动作等待html要求,并采取行动将被混淆,如果它会得到,例如json。所以为了避免这种情况,你必须添加format.json {},并在大括号中添加你想要呈现的信息。

编辑

更详细,你可以READ HEAR

相关问题