link_to:action =>’create’转到索引而不是’create’
我正在构建一个相当简单的配方应用程序来学习RoR,我试图通过单击链接而不是通过表单来允许用户保存配方,因此我通过link_to连接user_recipe控制器的“创建”function。
不幸的是,由于某种原因,link_to正在调用索引函数而不是create。
我把link_to写成了
'create',: recipe_id => @recipe%>
此链接位于user_recipes / index.html.erb上,并且正在调用同一控制器的“create”function。 如果我包含:controller,它似乎没有什么区别。
控制器看起来像这样
def指数 @recipe = params [:recipe_id] @user_recipes = UserRecipes.all#更改以查找db中的多个用户 respond_to do | format | format.html #index.html.erb format.xml {render:xml => @recipes} 结束 结束 def创建 @user_recipe = UserRecipe.new @ user_recipe.recipe_id = params [:recipe_id] @ user_recipe.user_id = current_user respond_to do | format | if @ menu_recipe.save format.html {redirect_to(r,:notice =>'菜单已成功创建。')} format.xml {render:xml => @ menu,:status =>:created,:location => @menu} 其他 format.html {render:action =>“new”} format.xml {render:xml => @ menu.errors,:status =>:unprocessable_entity} 结束 结束
在标准REST方案中,索引操作和创建操作都具有相同的URL( /recipes
),并且仅在使用GET访问索引并且使用POST访问create时不同。 所以link_to :action => :create
将生成一个指向/recipes
的链接,这将导致浏览器在单击时执行/recipes
的GET请求,从而调用索引操作。
要调用create动作,请使用link_to {:action => :create}, :method => :post
link_to
link_to {:action => :create}, :method => :post
,明确告诉link_to
您想要发布请求,或者使用带有提交按钮而非链接的表单。
假设您在路径文件中设置了默认资源,即类似这样的东西
resources :recipes
以下将生成一个将创建配方的链接; 即将被路由到创建操作。
<%= link_to "Create Recipe", recipes_path, :method => :post %>
为此,需要在浏览器中启用JS。
以下将生成一个显示所有食谱的链接; 即将被路由到索引操作。
<%= link_to "All Recipes", recipes_path %>
这假设默认值是Get HTTP请求。