带有rails的多个表单行

时间:2017-09-18 16:35:31

标签: javascript ruby-on-rails

我正在构建一个Web应用程序,允许用户添加他们正在进行的课程和作业。我希望他们能够一次添加多个作业。为此,我有一个表单,我将添加javascript以添加更多输入字段。

    <%= form_tag(@assignment) do |f| %>
      <div class="hidden-form">
        <input type="hidden" name="course_id" value="<%= @course.id %>">
      </div>
      <div id="assignments">
        <div class="assignment-row">
            <div class="fields">
                <div class="col-sm-6 col-xs-12">
                    <div class="form-group">
                        <%= label_tag :name %>
                        <%= text_field_tag "assignments[][name]", "", class: "form-control" %>
                    </div>
                </div>
                <div class="col-sm-3 col-xs-6">
                   <div class="form-group">
                    <%= label_tag :weight %>
                    <%= text_field_tag "assignments[][weight]","", class: "form-control" %>
                   </div>
                </div>
                <div class="col-sm-3 col-xs-6">
                    <div class="form-group">
                        <%= label_tag :grade %>
                        <%= text_field_tag "assignments[][grade]","", class: "form-control" %>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-12" style='margin: 15px 0;'>
        <button class="btn btn-primary btn-full" id="add-assignment-form">
        Add Assignment <span class="fa fa-plus"></span>
        </button
    </div>
   </div>
   <div class="footer">
    <div class="col-sm-6">
    <a href="#" class="btn btn-full btn-default">Skip</a>
        </div>
    <br class="visible-xs">
    <div class="col-sm-6 text-right">
    <%= submit_tag("Save and Continue", class: "btn btn-full btn-success") %>
    </div>
  <% end %>

然后让我的任务控制器尝试遍历每个表单并保存每个条目。

def create
    @assignments = params[:assignments]
    @course = Course.find(params[:course_id])

    @assignments.each do |assignment| 
      @a = @course.assignments.new(assignment)
      if @a.save 
        respond_to do |format| 
          format.html { redirect_to root_path, alert: "Course was added!" }
        end
      end
    end

  end

我遇到了麻烦,因为我一直在 error:ForbiddenAttributesError

我真的不知道如何解决这个问题。我已经尝试将它发送到我的Assignment控制器中的清洁剂但没有任何效果......

注意:我还没有添加动态表单javascript功能。只是想让条目先工作......

1 个答案:

答案 0 :(得分:0)

您必须允许参数...以下内容应该有效:

def create
  @course = Course.find(params[:course_id])

  assignments_params.each do |assignment| 
    @a = @course.assignments.new(assignment)
    if @a.save 
      respond_to do |format| 
        format.html { redirect_to root_path, alert: "Course was added!" }
      end
    end
  end
end


private

def assignments_params
  params.permit(assignments: [:name, :weight, :grade])
end