Prev | Current Page 343 | Next

Brad Ediger

"Advanced Rails"


Figure 7-3. List of products
HTTP verb URI Rails method
GET /products index
GET /products/1 show
GET /products/new new
GET /products/1/edit edit
RESTful Rails | 227
Note that the Rails convention is to create a resource by POSTing to its parent (collection)
resource; this is necessary because the server chooses the newly created
resource??™s URI (as it contains an arbitrary ID).
The controller actions make use of the HTTPresponse codes most appropriate for
error messages, success messages, and redirects. Rather than just being useful, as is
often the case with human-consumable web applications, status codes are absolutely
essential for web services. Client libraries such as ActiveResource rely on them to
take the appropriate actions.
One important addition to the old-style Rails scaffolded controllers is the use of
respond_to to send a different content type depending on the Accept header and possible
format parameters in the URI (such as /products.xml).
app/controllers/products_controller.rb
# POST /products
# POST /products.xml
def create
@product = Product.new(params[:product])
respond_to do |format|
if @product.save
flash[:notice] = 'Product was successfully created.'
format.html { redirect_to product_url(@product) }
format.xml { render :xml => @product, :status => :created,
:location => product_url(@product) }
else
format.html { render :action => "new" }
format.


Pages:
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355