Datasheet

Chapter 1: Building Resources
14
I mentioned earlier that you could have code other than the format methods inside the respond_to
block, and this example shows one reason why you might want to do that. The actual saving of the
recipe takes place inside that block. If the
save is successful, then the HTML response simply redirects to
the
show method. Rails infers that you want to show the object because the only argument to redirect_
to
is the object itself, and it uses REST routing to determine the unique URL for that object. The XML
response returns the object as XML with a couple of extra headers containing additional information.
If the
save is not successful, the HTML response is to show the new form again, and the XML response
is to send the errors and status via XML.
In case you are wondering why the
create method needs to support an XML format, the answer is to
allow new objects to be created remotely via a separate web services client that might be dealing with
your recipe server via XML.
Update
The update method is nearly identical to the create method, except that instead of creating a new
recipe, it finds the existing recipe with the expected ID, and instead of calling
save , it calls update_
attributes
. Oh, and the XML output is slightly different. The update method is as follows:
# PUT /recipes/1
# PUT /recipes/1.xml
def update
@recipe = Recipe.find(params[:id])
respond_to do |format|
if @recipe.update_attributes(params[:recipe])
flash[:notice] = ‘Recipe was successfully updated.’
format.html { redirect_to(@recipe) }
format.xml { head :ok }
else
format.html { render :action = > “edit” }
format.xml { render :xml = > @recipe.errors,
:status = > :unprocessable_entity }
end
end
end
Delete
Finally, delete . The default method doesn t check for success or failure of delete ; for an HTML
request, it redirects to the index page via the
recipes_url helper. An XML request gets a header
signaling success. Here s an example of the
delete method:
# DELETE /recipes/1
# DELETE /recipes/1.xml
def destroy
@recipe = Recipe.find(params[:id])
@recipe.destroy
c01.indd 14c01.indd 14 1/30/08 4:02:25 PM1/30/08 4:02:25 PM