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

(Tuis.) #1

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


Let’s examine the routes that make this work:


config/routes.rb
map.resources :carts do |cart|
cart.resources :products, :controller => 'line_items'
end


Because we are conforming to the Rails conventions of how RESTful routes should
work, there is very little manual configuration here. We get a lot “for free,” just for
following the conventions:



  • Incoming requests are mapped to the proper controller based not only on the
    URI but also on the HTT Pmethod used. (Some browsers and proxies do not
    support HTT Pmethods other thanGETandPOST; we will see later how Rails
    works around this.)

  • We get named routes completely for free, including the ability to route to a spe-
    cific representation such as XML:
    carts_path # => /carts


cart_path(some_cart) # => /carts/123
formatted_cart_path(some_cart, :xml) # => /carts/123.xml

products_path(some_cart) # => /carts/123/products
product_path(some_cart, some_product) # => /carts/123/products/456


  • The routing system pre-populates theparamshash with the ID variables we
    need, named appropriately. So, for a request to/carts/123/products/456, the
    paramshash will contain the pairs:cart_id => 123and:id => 456. We can use a
    before_filterin the controller to pick these off and retrieve them from the
    database, cleaning up the controller code.


Later in this chapter, we will explore the Rails RESTful routing system in detail. But
now, let’s take a look at the controllers that power the cart system. For simplicity, we
will ignore any responses that we might render in the real world, and instead focus
on sending correct HTT Presponse codes with no response body. (For this reason,
we have left out any kind of “view cart” action also.)


app/controllers/carts_controller.rb
class CartsController < ApplicationController


POST /carts


def create
@cart = Cart.create


Return 201 Created to indicate success; point to location of new cart


render :nothing => true, :status => :created, :location => cart_path(@cart)
end


# DELETE /carts/:id
def destroy
@cart = Cart.find(params[:id])
@cart.destroy
# Return 200 OK to indicate successful delete
render :nothing => true
Free download pdf