My Web Log Book

Responding with non-empty JSON when updating a resource via PUT in Rails 3

Rails 3 responds with an empty object when making PUT requests to update a resource. This could be undesirable for some cases, and certainly is in our case where expect the JSON representation of the modified object as the response.

The quick-fix is easy - we override the default behavior of respond_with using a block that returns forces the response to be the complete JSON object.

respond_with(@program) do |format|
  format.json {
    if @program.valid?
      render json: @program
    else
      render json: @program.errors, status: :unprocessable_entity
    end
  }
end

A neater fix, at least for me, would be in Rails itself inside the Responder class. GET and POST requests already work as expected. For other requests Rails returns an empty response. This is how things look right now

# This is the common behavior for formats associated with APIs, such as :xml and :json.
def api_behavior(error)
  raise error unless resourceful?

  if get?
    display resource
  elsif post?
    display resource, :status => :created, :location => api_location
  elsif has_empty_resource_definition?
    display empty_resource, :status => :ok
  else
    head :ok
  end
end

Instead of responding with an empty resource for non GET/POST requests, we could have returned the resource itself for PUT requests as well. Here’s how my ideal solution would look like (notice the elsif put? line):

# This is the common behavior for formats associated with APIs, such as :xml and :json.
def api_behavior(error)
  raise error unless resourceful?

  if get?
    display resource
  elsif post?
    display resource, :status => :created, :location => api_location
  elsif put?
    display resource, :status => :ok
  elsif has_empty_resource_definition?
    display empty_resource, :status => :ok
  else
    head :ok
  end
end

Now what can I do to get this merged in Rails?

  1. vombat posted this