Ruby on Rails:我能否使用“link_to”调用创建操作?

20

我该如何正确地使用link_to调用create动作?我正在使用REST(map.resources :recipes)。下面是create动作的代码:

def create
  recipe = Recipe.create(:name => "French fries")
  redirect_to recipe
end

例如,我认为以下内容可能有效:

<%= link_to "Create a default recipe", recipe_path, :method => :post %>

我不确定那是否是建议的(甚至正确的)方法。有任何想法吗?

1个回答

31
那应该可以工作,如果你用recipes_path替换recipe_path。 如果查看rake routes的输出,应该会看到类似以下内容:
recipes GET /recipes(.:format) {:controller=>"recipes", :action=>"index"}
        POST /recipes(.:format) {:controller=>"recipes", :action=>"create"}

这是一个提示,即在创建操作的URL助手(“recipes_path”)中,控制器名称后面加上_path,并使用:method => :post,组成了该助手。相同的路径使用:method => :get(默认值)将映射到index操作。

请记住,如果禁用Javascript,则此方法无法工作,因为Rails实际上正在添加一个on_click处理程序来创建一个表单进行POST。与:confirm选项一起使用的删除链接也是如此。


非常感谢您的详细解释,zetetic!非常感谢! :) - sjsc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接