我正在构建一个相当简单的配方程序来学习RoR,并且我试图让用户通过单击链接而不是通过表单来保存配方,因此我通过link_to连接了user_recipe控制器的“创建”功能。
由于某种原因,link_to正在调用索引函数而不是create。
我写了link_to as
<%= "save this recipe", :action => 'create', :recipe_id => @recipe %>
此链接位于user_recipes / index.html.erb上并正在调用同一控制器的“创建”功能。如果我包含:控制器,它似乎没有什么区别。
控制器看起来像这样
def index
@recipe = params[:recipe_id]
@user_recipes = UserRecipes.all # change to find when more than one user in db
respond_to do |format|
format.html #index.html.erb
format.xml { render :xml => @recipes }
end
end
def create
@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 => 'Menu was successfully created.') }
format.xml { render :xml => @menu, :status => :created, :location => @menu }
else
format.html { render :action => "new" }
format.xml { render :xml => @menu.errors, :status => :unprocessable_entity }
end
end
发布于 2018-05-08 13:59:42
在标准REST方案中,索引操作和创建操作都具有相同的url(/recipes
),并且仅在使用GET访问索引和使用POST访问create时不同。因此,link_to :action => :create
只需简单地生成一个链接,/recipes
浏览器就会/recipes
在单击时执行GET请求,从而调用索引操作。
要调用create action use link_to {:action => :create}, :method => :post
,link_to
明确地告诉你需要一个post请求,或者使用一个带有submit按钮而不是链接的表单。
发布于 2018-05-08 14:48:36
假设你有你的路由文件中设置的默认资源,即类似的东西
resources :recipes
以下内容将生成一个链接来创建一个配方; 即将被路由到创建操作。
<%= link_to "Create Recipe", recipes_path, :method => :post %>
为此,JS需要在浏览器中启用。
以下内容将生成一个显示所有食谱的链接; 即将被路由到索引操作。
<%= link_to "All Recipes", recipes_path %>
这假定默认是一个Get HTTP请求。
https://stackoverflow.com/questions/-100008407
复制相似问题