Datasheet
Chapter 1: Building Resources
13
New
The default new method is similar to show , except a new recipe object is created:
# GET /recipes/new
# GET /recipes/new.xml
def new
@recipe = Recipe.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml = > @recipe }
end
end
Edit
The default edit method is extremely simple because it does not have an XML representation defined,
so the traditional Rails default behavior happens automatically, and a
respond_to method is not
needed. Here ’ s an example:
# GET /recipes/1/edit
def edit
@recipe = Recipe.find(params[:id])
end
Create
The create method is more complicated because it needs to output different information depending on
whether the creation is successful. The new recipe object is created based on the incoming parameters,
and then it is saved to the database. For example:
# POST /recipes
# POST /recipes.xml
def create
@recipe = Recipe.new(params[:recipe])
respond_to do |format|
if @recipe.save
flash[:notice] = ‘Recipe was successfully created.’
format.html { redirect_to(@recipe) }
format.xml { render :xml = > @recipe,
:status = > :created,
:location = > @recipe }
else
format.html { render :action = > “new” }
format.xml { render :xml = > @recipe.errors,
:status = > :unprocessable_entity }
end
end
end
c01.indd 13c01.indd 13 1/30/08 4:02:24 PM1/30/08 4:02:24 PM