Prev | Current Page 306 | Next

Brad Ediger

"Advanced Rails"


We take great care to return the proper HTTPresponse status codes upon success so
that the client knows exactly which action was taken. On creation of a cart, we render
with a 201 Created status code and use the Location header to point to the newly
created cart. On cart deletion, we render a 200 OK to tell the client that the request
was successful.
The LineItemsController is slightly more complex, as line item resources are nested
within a cart. We use a set of before_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.


Pages:
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318