为什么Rails想要为JSON PUT请求返回"head:no_content"?

gog*_*n13 21 ruby-on-rails

运行后我
rails generate scaffold User
在Rails 3.2.11中生成的控制器函数用于更新用户,如下所示:

def update
  @user = User.find(params[:id])

  respond_to do |format|
    if @user.update_attributes(params[:user])
      format.html { redirect_to @user, notice: 'User was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: "edit" }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我很好奇的是返回head :no_content成功的JSON更新请求.我做了一些谷歌搜索,因为我猜这是某种RESTful属性,不返回更新的对象,但我找不到任何声称是这种情况.

为什么这是默认值,而不是在更新后返回User对象的JSON表示?

0x4*_*672 18

好问题,显然目的是返回一个空状态的HTTP状态代码200,请参阅此讨论.可能出于简洁或安全目的.head :no_content似乎用空体创建HTTP响应200(成功),返回此响应头:

Status Code:200 OK
Run Code Online (Sandbox Code Playgroud)

另见这个相关问题.

  • 我实际上看到`head:no_content`返回204 No Content,这似乎没有触发'ajax:success`事件. (2认同)
  • 如果要显式返回 200,请使用“head 200”。即使 `head :ok` 也会在后续请求中返回 304 notmodified。 (2认同)
  • `head :ok` 似乎总是为我返回 200。 (2认同)