我创建了一个表单来编辑Rails应用程序中的嵌套资源。表单可以正确渲染,并且提交按钮可以与create动作的表单一起使用,但是在应用到edit动作时会引起注意。没有错误被触发,页面也没有改变,因此很难找出问题所在。类似的问题可能是语法错误的结果,但在这种情况下我似乎找不到一个问题,但是,我可能会遗漏一些东西。下面是有问题的表格。
<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语句不是问题。任何帮助表示赞赏!
答案 0 :(得分:1)
我能够解决问题。由于控制器中对更新操作的定义不完整,因此提交按钮不起作用。代替...
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
答案 1 :(得分:0)
更改<%= form_with model: [ @recipe, @recipe.ingredients.build ], local: true do |form| %>
到<%= form_for [ @recipe, @recipe.ingredients.build ] do |form| %>