Datasheet

Chapter 1: Building Resources
36
The tests are very similar to what you d use for the normal edit and update, just with different URLs. The
response for the
update method is the ingredient display string, not a redirect to the show ingredient
page, which enables the updated ingredient to be inserted back into place on the recipe page. In the
interest of full disclosure among friends, I should reveal that I didn t actually develop this part strictly
test - first I played around with the layout within the recipe page a little bit before going back and
writing the test.
Because this is a new action for a RESTful controller, new routes have to be added in the
routes.rb file.
Modify it as follows:
map.resources :recipes do |recipes|
recipes.resources :ingredients,
:member = > {:remote_edit = > :get, :remote_update = > :put}
end
This creates a new remote_edit route that responds to GET , and a remote_update route that
responds to
PUT . Each of these routes gets a named method to refer to it: remote_edit_recipe_
ingredient_path
and remote_update_recipe_ingredient_path . Run the rake routes command
for full details.
Both of these methods need controller methods and views. The controller methods are quite simple, and
go in
app/controller/ingredient_controller.rb as follows:
def remote_edit
edit
end
You can t get much simpler than that. The remote_edit method uses the same method of getting its
ingredient as
edit does, so in the interest of avoiding cut and paste, I just call the other method directly.
The next step would be another
before_filter , which would make both methods empty.
There s also the following view for
remote_edit , keeping things on as few lines as possible:
< % remote_form_for(@ingredient,
:url = > remote_update_recipe_ingredient_path(@recipe, @ingredient),
:update = > “ingredient_#{@ingredient.id}”) do |f| % >
< table >
< tr >
< th class=”subtle” > Amount < /th >
< th class=”subtle” > Unit < /th >
< th class=”subtle” > Ingredient < /th >
< th class=”subtle” > Directions < /th >
< /tr >
< tr >
< td > < %= f.text_field :amount, :size = > “5” % > < /td >
< td > < %= f.text_field :unit, :size = > “10” % > < /td >
< td > < %= f.text_field :ingredient, :size = > “25” % > < /td >
< td > < %= f.text_field :instruction, :size = >
“15” % > < /td >
< td > < %= f.submit “Update” % > < /td >
< /tr >
< /table >
< % end % >
c01.indd 36c01.indd 36 1/30/08 4:02:31 PM1/30/08 4:02:31 PM