Rails 4: 为字段循环

Rails 4: loop for fields for

模特是

has_many :questions
accepts_nested_attributes_for :questions

控制器

params.require(:survey).permit(:title,:description,questions_attributes: [:title])

视图是

<%= f.fields_for :questions,@survey.questions.build do |question| %>
  <div class="form-group">
   <label class="col-lg-12 control-label" for="">Title</label>
   <p><%= question.text_field :title %></p>
  </div>
<% end %>

通过这个我只输入一个问题 time.How 我在 it.I 中添加了多次问题 我无法理解我用 JavaScript 做它并制作任何按钮或我的方式这样做?

您可以使用 "nested_form" gem 添加多个问题,如下所示:-

# Add gem in Gemfile and run bundle install
gem "nested_form"

在视图中:-

<%= nested_form_for @survey do |f| %>
    <%= f.fields_for :questions do |question| %>
        <div class="form-group">
            <label class="col-lg-12 control-label" for="">Title</label>
            <p><%= question.text_field :title %></p>
            <%= question.link_to_remove "Remove this answer" %>
        </div>
    <% end %>
    <%= f.link_to_add "Add more questions", :questions %>
<% end %>