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

(Tuis.) #1
RESTful Rails | 227

Note that the Rails convention is to create a resource byPOSTing to its parent (collec-
tion) 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 HTT Presponse 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_toto send a different content type depending on theAcceptheader and pos-
sible 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.xml { render :xml => @product.errors }
end
end
end

Here we see the standard use ofrespond_to; theformat.htmlandformat.xmlcalls are
intermingled with standard Ruby controller code. By default, this RESTful controller
looks at theAcceptheader to determine whether to render its responses as HTML or
XML. We can add more representations simply by adding aformatdirective and
appropriate templates. For example, using the built-in Rails JSON serialization func-
tions, we can add a simple JSON representation of a newly created object:


format.js { render :json => @product.to_json, :status => :created,
:location => product_url(@product) }

POST /products create
PUT /products/1 update
DELETE /products/1 destroy

HTTP verb URI Rails method
Free download pdf