【问题标题】:How can I get multiple input fields for my form that are unique?如何为我的表单获取多个唯一的输入字段?
【发布时间】:2018-05-01 15:34:23
【问题描述】:

我正在构建一个食谱应用程序,用户可以在其中选择预先存在的成分,如果找不到该成分,用户可以选择在输入字段上记下成分名称。我希望表单最多有 5 个输入字段。

我看到有人问过类似的问题,但他们的解决方案没有奏效。 q1

q2

这是我目前得到的,我尝试了两种方法。

<%=f.fields_for :ingredients do |ing|%>
    <%= ing.label :name, "Enter ingredient name"%>
    <br>
    <%= ing.text_field :name%>
 <%end%>

 <%=f.fields_for :recipe_ingredients do |ri|%>
    <%=ri.fields_for :ingredient do |ing|%>
        <%=ing.label :name, "enter ing name"%>
        <%=ing.text_field :name%>
    <%end%>
 <%end%>

recipes_controller.rb

def new
    @recipe = Recipe.new
    5.times do 
        @recipe.recipe_ingredients.build.ingredient
    end
    5.times do 
        @recipe.ingredients.build
    end
end

协会

一个食谱通过 recipe_ingredients 包含许多成分。

一种成分通过 recipe_ingredients 有许多配方。


对于这两种情况,我只返回 1 个输入字段,我该怎么做?

【问题讨论】:

  • 使用f.fields_for @recipe.recipe_ingredients
  • 你知道this吗?它总是有帮助的。
  • 我尝试了@recipe.recipe_ingredients 修改,但仍然没有改变,我正在查看 iGian 页面,但我无法让它为我工作,或者至少我找不到控制器文件。

标签: ruby-on-rails


【解决方案1】:

事实证明这两种方法都有效。我所缺少的只是在我的 Recipe 模型类中添加“accepts_nested_attributes_for”。

【讨论】:

    猜你喜欢
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多