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

(Tuis.) #1

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


Note that our old code has no action for “create cart,” but the new code requires that
as an explicit step. This is a consequence of RESTful design; we now realize that the
cart resource (along with its child, the cart-product or line-item resource) is a sepa-
rate resource and should be treated as such. Rather than treating cart creation as a
side effect of some other action, we explicitly make cart creation a client-initiated
action.


Also notice that the old code has RPC-style URIs; they contain the method name.
The new URIs have a more proper separation of concerns. The HTT Pmethod
contains the verb or action; the URI contains the name of the object of that action
(the resource); and theoptional request body contains information pertaining to the
resource.


Now that we have decided on a set of URLs for the application, we can start writing
code. First, we have identified the types of resources that will be involved. They were
implied previously, but we will describe them:


Cart factory (/carts)
This resource is responsible for generating carts. An emptyPOSTto/cartswill
create a new cart and return its URI in the HTTPLocation header.


Cart (/carts/4)
Represents a cart; in this model, shopping cart state is kept explicitly in this
resource rather than in the user’s session.


Line Item (/carts/4/products/123)
Represents an instance of a product in a user’s cart. Subordinate to (nested
within) the cart resource.


These three types of resources are just that—types, not resources
themselves. Although there is only one “cart” resource type, there are
potentially infinitely many “cart” resources (/carts/4,/carts/5, and
so on). This is an important distinction to keep in mind. Typically,
resource types will either have cardinality one (such as our “cart fac-
tory” type) or infinity (as with our “carts” type).

In Rails, the first two types are handled by the same controller, by convention. Oper-
ations on the collection as a whole (such asPOST /carts) and on its members (such as


Action Non-RESTful URI (POST method) RESTful method and URI
Create cart (N/A) POST /carts
Add item /carts/add_product/123 PUT /carts/4/products/123
Update quantity /carts/update_quantity/
123?quantity=2

PUT /carts/4/products/123
line_item[quantity]=2
Remove item /carts/remove_item/123 DELETE /carts/4/products/123
Empty cart /carts/empty_cart DELETE /carts/4
Free download pdf