Rails的Simple_form_for hidden_​​field值不正确

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在我正在测试的实例中)。

当形式实际上被渲染,该值是正确的: enter image description here

然而,当记录是创建ingredient仍然与nil一个recipe_id创建。任何智慧,以什么是错的?

+0

您正在寻找在错误的隐藏字段。你的是'.form-inputs' div中的,就在选定的隐藏输入 – MrYoshiji

+0

@MrYoshiji之下,这是正确的,并且OP已被更新。不幸的是,这使问题更加令人烦恼! – Liz

+0

'f.hidden_​​field:recipe'应该是'f.hidden_​​field:recipe_id' – MrYoshiji

f.hidden_field :recipef.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