28

After I run
rails generate scaffold User
The generated controller function in Rails 3.2.11 for updating a user looks like this:

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

The line I'm curious about is returning head :no_content for a successful JSON update request. I've done some googling, as I was guessing that this is some sort of RESTful property, to not return the updated object, but I couldn't find anything that claimed that was the case.

Why is this the default, versus returning the JSON representation of the User object post-update?

goggin13
  • 7,876
  • 7
  • 29
  • 44

1 Answers1

22

Good question, apparently the purpose is to return a HTTP status code 200 with an empty body, see this discussion. Maybe for brevity or security purposes. head :no_content seems to create a HTTP response 200 (success) with an empty body, returning this response header:

Status Code:200 OK

see also this related question.

Community
  • 1
  • 1
0x4a6f4672
  • 27,297
  • 17
  • 103
  • 140
  • 3
    I am actually seeing `head :no_content` return a 204 No Content, which doesn't seem to fire the `ajax:success` event. – James McMahon Nov 13 '13 at 14:37
  • 2
    If you want to explicitly return 200, use `head 200`. Even `head :ok` will return 304 not modified on subsequent requests. – Damien Roche Aug 13 '14 at 00:25
  • @DamienRoche on a `GET` request, you will want a `304 Not Modified` to be returned if the resources has truly not been modified, as this is needed for HTTP caching to work. To ensure best results set expires/last-modified headers and/or etag headers too. – xentek Jul 01 '15 at 18:13
  • that `:ok` should be changed, it's confusing that it returns 304 on subsequent requests... which conditions make it 304? – sites Aug 16 '16 at 02:18
  • 2
    `head :ok` seems to return 200 always for me. – sites Aug 16 '16 at 02:19