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

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

# Remove specified item from cart
session[:cart].delete product_id.to_i
end

def empty
session[:cart] = Cart.new
end

protected

def set_cart
session[:cart] ||= Cart.new
end
end

config/routes.rb
map.add_to_cart '/carts/add_product/:id',
:controller => 'carts', :action => 'add_product'
map.update_cart_quantity '/carts/update_quantity/:id',
:controller => 'carts', :action => 'update_quantity'
map.remove_product '/carts/remove_product/:id',
:controller => 'carts', :action => 'remove_product'
map.empty_cart '/carts/empty',
:controller => 'carts', :action => 'empty'


We are using named routes here so that we gain the benefit of the Rails
named URI generators. For non-RESTful Rails applications, named
routes are much preferred over the default:controller/:action/:id
route, as they decouple URIs from their implementation. For example,
the “remove product” action in the views would typically be coded as
follows:
link_to "Remove Product",
remove_product_path(:id => @product.id),
:method => :post
If all links are generated through the Rails named route mechanism,
then URIs can be changed simply by changing the template in the
routes file, without touching any of the code that links to the page
being changed.

Though this is a relatively clean implementation, it still requires the use of persistent
session storage on the server. This is not optimal, for the reasons we discussed
earlier.


In addition, this code could use some architectural cleanup. Because a resource can
be anything, we will choose to model the cart as a resource itself. Rather than URIs
affecting the product, which have effects on the cart in the session, we choose
URIs thatexplicitly model their effects on our newly created cart resource. Using
some standard RESTful Rails URI conventions, we come up with the following set of
actions.

Free download pdf