Rails的Simple_form_for hidden_field值不正确
问题描述:
我在我的Rails应用程序的格式如下:Rails的Simple_form_for hidden_field值不正确
<%= simple_form_for(@ingredient) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
...
<%= f.hidden_field :recipe, value: @recipe.id %>
</div>
<div class="form-actions text-center">
<%= f.button :submit %>
</div>
<% end %>
我在我的控制器有这样的:
@recipe = Recipe.find(params[:id])
@ingredient = Ingredient.new
@ingredients = Ingredient.where(user_id: current_user.id, recipe_id: @recipe.id)
而且我与byebug测试的@recipe.id
出来的一个数字(4
在我正在测试的实例中)。
然而,当记录是创建ingredient
仍然与nil
一个recipe_id
创建。任何智慧,以什么是错的?
答
的f.hidden_field :recipe
应f.hidden_field :recipe_id
答
前面已经回答了,你应该使用f.hidden_field:recipe_id
但我会添加一个加,试着像这样使用:
配料控制器:
@ingredient = Ingredient.new({:recipe_id => @recipe.id})
在成分观点:
f.hidden_field :recipe_id
以这种方式,您不需要实例化视图中的配方。这也适用于你的编辑视图!它保持清楚!
+0
谢谢你的回答。但是,使用正确的表单输入更新OP后,即使html列出值为4,错误仍然存在(“成分”是用'nil'的recipe_id'创建的)。 – Liz
您正在寻找在错误的隐藏字段。你的是'.form-inputs' div中的,就在选定的隐藏输入 – MrYoshiji
@MrYoshiji之下,这是正确的,并且OP已被更新。不幸的是,这使问题更加令人烦恼! – Liz
'f.hidden_field:recipe'应该是'f.hidden_field:recipe_id' – MrYoshiji