Prev | Current Page 344 | Next

Brad Ediger

"Advanced Rails"

xml { render :xml => @product.errors }
end
end
end
Here we see the standard use of respond_to; the format.html and format.xml calls are
intermingled with standard Ruby controller code. By default, this RESTful controller
looks at the Accept header to determine whether to render its responses as HTML or
XML. We can add more representations simply by adding a format directive and
appropriate templates. For example, using the built-in Rails JSON serialization functions,
we can add a simple JSON representation of a newly created object:
format.js { render :json => @product.to_json, :status => :created,
:location => product_url(@product) }
POST /products create
PUT /products/1 update
DELETE /products/1 destroy
HTTP verb URI Rails method
228 | Chapter 7: REST, Resources, and Web Services
The render :json variant renders the given text and sets the response??™s content type
to text/x-json. We should also present a JSON version of our error codes upon
error, in the else block above:
format.js { render :json => @product.errors.to_json,
:status => :unprocessable_entity }
We send an HTTPresponse code of 422 Unprocessable Entity here.
The 422 code is not in the HTTP/1.1 specification; it was added later
by WebDAV. However, it is the most appropriate response code to our
situation (the client has submitted a resource that is unprocessable),
and even Roy Fielding agreed that 422 is the most appropriate code for
this sort of situation.


Pages:
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356