如何在rails3路由中使用匹配的动作名称

时间:2010-09-14 22:45:56

标签: ruby-on-rails

我有一条路 http://localhost:3000/recipes/1/ingredient/3

在我的路线中,我定义了

match  "/recipes/:recipe_id/ingredients/:id" => "ingredients#show"

但是,我认为我不应该在我的路线文件中定义每个动作,我不应该为'ingredients #stow'创建一个单独的条目,而不是'ingredients#edit'。

如何定义我的匹配,以便它采用默认值或使用link_to中定义的操作。

目前,我的link_to定义为

<%= link_to 'Edit Ingredient', [@ingredient.recipe, @ingredient],
                                  :method => :edit,
                                  :controller => :ingredients %>

<%= link_to 'Edit Ingredient', [@ingredient.recipe, @ingredient],
                                  :method => :show,
                                  :controller => :ingredients %>

1 个答案:

答案 0 :(得分:3)

我认为你正在寻找资源而不是匹配......

resources :recipes do
  resources :ingredients
end

给你:

recipe_ingredients GET    /recipes/:recipe_id/ingredients(.:format)          {:action=>"index", :controller=>"ingredients"}
    recipe_ingredients ingredient   /recipes/:recipe_id/ingredients(.:format)          {:action=>"create", :controller=>"ingredients"}
 new_recipe_ingredient GET    /recipes/:recipe_id/ingredients/new(.:format)      {:action=>"new", :controller=>"ingredients"}
edit_recipe_ingredient GET    /recipes/:recipe_id/ingredients/:id/edit(.:format) {:action=>"edit", :controller=>"ingredients"}
     recipe_ingredient GET    /recipes/:recipe_id/ingredients/:id(.:format)      {:action=>"show", :controller=>"ingredients"}
     recipe_ingredient PUT    /recipes/:recipe_id/ingredients/:id(.:format)      {:action=>"update", :controller=>"ingredients"}
     recipe_ingredient DELETE /recipes/:recipe_id/ingredients/:id(.:format)      {:action=>"destroy", :controller=>"ingredients"}
         recipes GET    /recipes(.:format)                           {:action=>"index", :controller=>"recipes"}
         recipes ingredient   /recipes(.:format)                           {:action=>"create", :controller=>"recipes"}
      new_recipe GET    /recipes/new(.:format)                       {:action=>"new", :controller=>"recipes"}
     edit_recipe GET    /recipes/:id/edit(.:format)                  {:action=>"edit", :controller=>"recipes"}
          recipe GET    /recipes/:id(.:format)                       {:action=>"show", :controller=>"recipes"}
          recipe PUT    /recipes/:id(.:format)                       {:action=>"update", :controller=>"recipes"}
          recipe DELETE /recipes/:id(.:format)                       {:action=>"destroy", :controller=>"recipes"}

所以您的编辑操作变为:

<%= link_to 'Edit Ingredient', edit_recipe_ingredient_path(@ingredient.recipe, @ingredient) %>

并显示操作变为:

<%= link_to 'Edit Ingredient', [@ingredient.recipe, @ingredient] %>

否则,您必须执行以下操作:

<%= link_to 'Edit Ingredient', :controller => :ingredients, :action => :show, :id => @ingredient.id, :recipe_id => @ingredient.recipe %>