to_i] += quantity.to_i
end
def update_quantity
product_id = params[:id]
quantity = params[:quantity]
# Set cart quantity to provided quantity
session[:cart][product_id.to_i] = quantity.to_i
end
def remove_product
product_id = params[:id]
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.
Pages:
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312