2017-09-18 76 views
0

我有一個網絡應用程序,我正在構建這將允許用戶添加課程和他們正在進行的任務。我希望他們能夠一次添加多個作業。要做到這一點,我有一個表單,我將添加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功能。只是想獲得第一項工作...

+0

您必須定義和使用strong_params。 –

+0

我將如何使用具有多個條目的strong_params? –

+0

許可params。請參閱http://api.rubyonrails.org/v5.1/classes/ActionController/StrongParameters.html – krishnar

回答

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