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

(Tuis.) #1
What Is REST? | 203

end
end

TheCartsControllerhandles the “create a cart” (POST /carts) and “empty cart”
(DELETE /carts/:id) actions. The routing system maps the requests to the corre-
sponding CRUD actions; they use their traditional Rails names (index,show,new,
create,edit,update, anddestroy).


We take great care to return the proper HTT Presponse status codes upon success so
that the client knows exactly which action was taken. On creation of a cart, we ren-
der with a201 Createdstatus code and use theLocationheader to point to the newly
created cart. On cart deletion, we render a200 OKto tell the client that the request
was successful.


TheLineItemsControlleris slightly more complex, as line item resources are nested
within a cart. We use a set ofbefore_filters to retrieve the corresponding records:


app/controllers/line_items_controller.rb
class LineItemsController < ApplicationController


Nested RESTful routes set params[:cart_id] on each action.


Use that param to retrieve the cart.


before_filter :find_cart


# For member actions (update, destroy), find the line item
# by looking at params[:id].
before_filter :find_line_item, :only => [:update, :destroy]

# PUT /carts/:cart_id/products/:id
def update
# Create line item if it does not exist
@line_item ||= LineItem.new(:cart_id => params[:cart_id],
:product_id => params[:id], :quantity => 1)

# Update attributes from params
@line_item.update_attributes params[:line_item]
render :nothing => true # Status: 200 OK
end

# DELETE /carts/:cart_id/products/:id
def destroy
@line_item.destroy
render :nothing => true
end

protected

def find_cart
@cart = Cart.find params[:cart_id]
end

def find_line_item
@line_item = @cart.line_items.find(params[:id])
end
end
Free download pdf