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

(Tuis.) #1

228 | Chapter 7: REST, Resources, and Web Services


Therender :jsonvariant renders the given text and sets the response’s content type
totext/x-json. We should also present a JSON version of our error codes upon
error, in theelse block above:


format.js { render :json => @product.errors.to_json,
:status => :unprocessable_entity }

We send an HTT Presponse 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. In addition, in Rails 2.0, ActiveResource treats a
422 response as a failed validation.

Now we will turn this simple web application into a client/server application. Here is
where the magic happens. We will disconnect the backend (ActiveRecord and data-
base access) from the front end (the user interface). The backend will become the
server, and the front end will become the client. The two will talk over HTT Pusing a
RESTful interface.


As the application is already set up to render XML when requested (via anAccept
header oftext/xmlor a format extension of.xml), no changes are needed to the server.
We can treat the server as a web service simply by requesting XML over HTTP. The
client will require some slight modifications to talk over a RESTful HTT Pinterface
rather than a database connection, but the changes will be very small as ActiveRe-
source was designed to have an ActiveRecord-like interface.


First, we will copy the entire project (the original of which will become the server)
into a separate directory, which will become the client:


$ cp -R products_example products_example_client

As mentioned previously, the server needs no modification at all. We can start it on
port 4000, which will become the location at which we access the web service:


$ cd products_example_client
$ script/server --port 4000

Now we can open up the code for the client and modify it to queryhttp://localhost:
4000/for products. We openapp/models/product.rb, which was a very straightforward
ActiveRecord model:


class Product < ActiveRecord::Base
end

We change this to an equivalently simple ActiveResource model, backed by the web
service that we have set up:


class Product < ActiveResource::Base
self.site = "http://localhost:4000/"
end
Free download pdf