So, for a request to /carts/123/products/456, the
params hash will contain the pairs :cart_id => 123 and :id => 456. We can use a
before_filter in 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 HTTPresponse 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
What Is REST? | 203
end
end
The CartsController handles the ???create a cart??? (POST /carts) and ???empty cart???
(DELETE /carts/:id) actions. The routing system maps the requests to the corresponding
CRUD actions; they use their traditional Rails names (index, show, new,
create, edit, update, and destroy).
Pages:
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317