Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
RESTful Rails | 223

the response belongs. The categories are divided in this way so that a client that does
not understand an obscure response code can infer some semanticinformation about
the status (for example, whether the request succeeded or failed, and whether the
request should be tried again) by examining the status code’s first digit.


1xx: Informational
These codes are used for protocol negotiations between client and server. This
series of status codes is not currently in wide use.


2xx: Success
A code in the 2xx series indicates that the request completed successfully. The
request may have either been processed immediately or accepted for processing.


3xx: Redirection
These codes indicate that the client must look elsewhere for the requested
resource. The new location is provided in theLocation response header.


4xx: Client Error
These codes indicate that the server cannot understand, cannot fulfill, or refuses
to fulfill the client’s request, apparently due to the client’s error.


5xx: Server Error
5xx response codes indicate that the server understood the request but is incapa-
ble of performing it, temporarily or permanently, due to a server error.


The advantage of using standardized codes, of course, is that everyone (theoreti-
cally) uses them and understands them. In particular, Rails uses a rich set of response
codes when requesting and providing data over a RESTful interface. ActiveResource,
for example, will respond to a 404 by raisingActiveResource::ResourceNotFound(a
parallel ofActiveRecord::RecordNotFound), and to a 422 by raisingActiveResource::
ResourceInvalid (upon failed validations).


ActiveResource: Consuming RESTful Services


One huge advantage of coding web services RESTfully is that clients can then con-
sume them using a standard interface. ActiveResource is a library, now part of edge
Rails, which abstracts RESTful resources using an ActiveRecord-like interface. It fits
well into the Rails model of building applications, and as long as the server was built
using RESTful Rails conventions, using ActiveResource is nearly transparent.


To demonstrate the power of ActiveResource, we will build a very simple applica-
tion (nothing more than a scaffolded interface to a set of ActiveRecord objects) to
manage a set of products in a fictional store. We will first build this as a basic
ActiveRecord application using RESTful principles; then we will use ActiveResource
to disconnect the backend web service from the front end interface.

Free download pdf