Prev | Current Page 304 | Next

Brad Ediger

"Advanced Rails"

We define
two instance methods on Cart, add_product (which adds quantity copies of the product
to the cart) and update_quantity (which sets the quantity of the existing product in the
cart to the provided quantity). The cart is emptied by deleting the Cart object (which
destroys it and its dependent LineItems, thanks to the :dependent => :destroy directive
on has_many). Similarly, an item is removed from the cart simply by destroying its corresponding
LineItem.
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 HTTPmethod used. (Some browsers and proxies do not
support HTTPmethods other than GET and POST; we will see later how Rails
works around this.)
??? We get named routes completely for free, including the ability to route to a specific
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 the params hash with the ID variables we
need, named appropriately.


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