Datasheet

Chapter 1: Building Resources
37
Notice the pathname in the result. This is app/views/ingredients/remote_edit.html.erb .
The following
remote_update method in the ingredient controller is a simplification of update (for one
thing, I m not concerned here with responding in formats other than HTML):
def remote_update
@ingredient = Ingredient.find(params[:id])
if @ingredient.update_attributes(params[:ingredient])
render(:layout = > false)
else
render :text = > “Error updating ingredient”
end
end
The view for this method is simply this:
< %= h @ingredient.display_string % >
The only rendered output of this method is the display string of the newly constructed ingredient or an
error message. The only reason it s in an
erb file at all is to allow access to the h method to escape out
HTML tags and prevent an injection attack.
Finally, the call to create this form has to be placed in the recipe
show.html.erb file. Here ’ s the
relevant chunk:
< div class=”ingredients” >
< h2 > Ingredients < /h2 >
< % for ingredient in @recipe.ingredients % >
< div class=”ingredient” >
< span id=”ingredient_ < %= ingredient.id % > >
< %= h ingredient.display_string % >
< /span >
< span class=”subtle” id=”edit_ < %= ingredient.id % > >
< %= link_to_remote “Edit”,
:url = >
remote_edit_recipe_ingredient_path(@recipe, ingredient),
:method = > :get,
:update = > “ingredient_#{ingredient.id}”% >
< /span >
< /div >
< % end % >
< /div >
Watch out for the :method parameter of the link_to_remote call. By default, link_to_remote sends
its request as a
POST , and I already specified that remote_edit was a GET . Other than that, the link_
to_remote
call is typical. The URL to call is specified using the new name generated by the new route,
and the DOM element to update is the preceding span containing the ingredient display string.
c01.indd 37c01.indd 37 1/30/08 4:02:32 PM1/30/08 4:02:32 PM