我创建了一个表单来编辑rails应用程序中的嵌套资源。表单正确呈现,提交按钮与创建操作的表单配合使用,但在应用于编辑操作时会导致注意发生。不会触发错误,页面也不会更改,因此很难找出问题所在。类似的问题接缝是语法错误的结果,但在这种情况下我似乎找不到一个,但是,我可能错过了一些东西。以下是有问题的表格。
<h1>Edit an Ingredient<h1>
<%= form_with model: [ @recipe, @ingredient ], local: true do |form| %>
<p>
<%= form.label :quantity %><br>
<%= form.text_field :quantity %>
</p>
<p>
<%= form.label :measurement %><br>
<%= form.text_area :measurement %>
</p>
<p>
<%= form.label :ingredientname %><br>
<%= form.text_area :ingredientname %>
</p>
<p>
<%= form.label :label %><br>
<%= form.text_area :label %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
<%= link_to 'Back', recipes_path %>
以及功能正常的"新"形式...
<h1>Add an Ingredient<h1>
<%= form_with model: [ @recipe, @recipe.ingredients.build ], local: true do |form| %>
<p>
<%= form.label :quantity %><br>
<%= form.text_field :quantity %>
</p>
<p>
<%= form.label :measurement %><br>
<%= form.text_area :measurement %>
</p>
<p>
<%= form.label :ingredientname %><br>
<%= form.text_area :ingredientname %>
</p>
<p>
<%= form.label :label %><br>
<%= form.text_area :label %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
<%= link_to 'Back', recipes_path %>
最后是相关的控制器...
class IngredientsController < ApplicationController
def new
@recipe = Recipe.find(params[:recipe_id])
end
def edit
@recipe = Recipe.find(params[:recipe_id])
@ingredient = @recipe.ingredients.find(params[:id])
end
def create
@recipe = Recipe.find(params[:recipe_id])
@ingredient = @recipe.ingredients.create(ingredient_params)
redirect_to recipe_path(@recipe)
end
def update
@recipe = Recipe.find(params[:recipe_id])
@ingredient = @recipe.ingredients.find(params[:id])
end
def destroy
@recipe = Recipe.find(params[:recipe_id])
@ingredient = @recipe.ingredients.find(params[:id])
@ingredient.destroy
redirect_to recipe_path(@recipe)
end
private
def ingredient_params
params.require(:ingredient).permit(:quantity, :measurement, :ingredientname, :label)
end
end
此外,表单在呈现时会正确填充,导致我相信这不是form_with语句的问题。任何帮助不胜感激!
我能够找到解决方案。由于控制器中更新操作的定义不完整,提交按钮不起作用。而不是。。。
def update
@recipe = Recipe.find(params[:recipe_id])
@ingredient = @recipe.ingredients.find(params[:id])
end
更新操作应定义为...
def update
@recipe = Recipe.find(params[:recipe_id])
@ingredient = @recipe.ingredients.find(params[:id])
if @ingredient.update(ingredient_params)
redirect_to @recipe
else
render 'edit'
end
end
更改<%= form_with model: [ @recipe, @recipe.ingredients.build ], local: true do |form| %>
到<%= form_for [ @recipe, @recipe.ingredients.build ] do |form| %>