Datasheet

Chapter 1: Building Resources
9
When you call one of these path or URL methods with a PUT or DELETE HTTP method, you must make
sure that the
link_to or redirect call also contains the option :method = > :delete or :method = >
:put
to ensure that the URL is properly sent by Rails ( link_to assumes GET ; the form methods and
link_to_remote assume POST ). If you are using the standard HTTP method, there s a shortcut, where
you just specify the object that is the target of the link:
link_to @recipe
You ll see examples of those calls when you examine the standard views that the generator has created.
Also, the methods that take an argument can take either an integer argument, in which case it ’ s assumed
to be the ID of the resource you are interested in, or they can take the resource object itself, in which case,
the ID is extracted for use in the URL or path. They can also take the usual key/value pairs, which are
converted to a query string for the request.
Nested Routes
You need to do a slight tweak of the routes to allow for the relationship between a recipe and its
ingredients. As the design currently stands, there s a strict one - to - many relationship between recipes
and ingredients, with an ingredient only being meaningful inside its specific recipe. To make your Rails
routes reflect that relationship more accurately, the routes can be nested in
routes.rb . Change your
routes.rb file so that the resource lines are as follows:
map.resources :recipes do |recipes|
recipes.resources :ingredients
end
With this nesting in place, Rails will generate similar routes for ingredients, but only with a recipe
attached at the beginning of the URL. For example, the URL to call the
index method for the ingredients
in a recipe will be as follows:
/recipe/1/ingredients
And the URL for showing, updating, and deleting would look like this:
/recipe/1/ingredient/1
The named methods for a nested resource are similar to the parent - level methods listed previously, but
they contain the parent resource name in the method, such as the following:
recipe_ingredient_url(@recipe, @ingredient)
edit_recipe_ingredient_url(@recipe, @ingredient)
The path - based methods are similar. Again, the methods can take either integer IDs or the actual resource
objects. This naming convention is pretty clear when the nesting isn t very deep or when the variables
c01.indd 9c01.indd 9 1/30/08 4:02:23 PM1/30/08 4:02:23 PM