2016-01-26 54 views
0

插槽有很多學生
我的形式:Rails的表單輔助意外PARAMS哈希

<%= form_for(@slot) do |f| %> 

    <% @slot.students.each do |student| %> 
    <%= f.fields_for student, index: student.id do |student_form| %> 
     ID: <%= student.id %> 
     Present: <%= student_form.check_box :present %><br> 
    <% end %> 
    <% end %> 

    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

和槽控制器得到這個PARAMS哈希:

"slot"=>{ 
"student"=>{"1"=>{"present"=>"0"}, 
"2"=>{"present"=>"0"}, 
"3"=>{"present"=>"0"}, 
"4"=>{"present"=>"0"}, 
"5"=>{"present"=>"0"}, 
"commit"=>"Update Slot", 
"id"=>"125251"} 

因爲我需要學生的ID,但我不知道知道我怎樣才能通過每個學生。這種方式對我來說更容易:

"slot"=>{ 
    "student"=>{{"id"=>"1","present"=>"0"}, 
    {"id"=>"2","present"=>"0"}, 
    {"id"=>"3","present"=>"0"}, 
    {"id"=>"4","present"=>"0"}, 
    {"id"=>"5","present"=>"0"}, 
    "commit"=>"Update Slot", 
    "id"=>"125251"} 

我該如何編輯表格?非常感謝。

回答

1

你想閱讀了有關fields_for collections

#app/views/slots/edit.html.erb 
<%= form_for @slot do |f| %> 

    <%= f.fields_for :students, @slot.students do |student_form| %> 
     ID: <%= student.id %> 
     Present: <%= student_form.check_box :present %><br> 
    <% end %> 

    <%= f.submit %> 
<% end %> 

以上應該工作。

如何查看是否爲的工作方式是在params散列中查找students_attributes。如果您的PARAMS沒有做_attributes附加,它不工作:

"slot"=>{ 
"students_attributes"=> 
    { 
    "1"=>{"present"=>"0"}, 
    "2"=>{"present"=>"0"}, 
    "3"=>{"present"=>"0"}, 
    "4"=>{"present"=>"0"}, 
    "5"=>{"present"=>"0"}, 
    } 
    "commit"=>"Update Slot", 
    "id"=>"125251"} 

這是怎麼fields_for應該工作。不構建關聯對象或不存在這些對象將阻止傳遞參數_attributes,從而防止accepts_nested_attributes_for根據需要更新字段。

-

你並不需要明確定義idsfields_for/accepts_nested_attributes_for應該爲你做的:

#app/models/slot.rb 
class Slot < ActiveRecord::Base 
    has_many :students 
    accepts_nested_attributes_for :students 
end 

#app/controllers/slots_controller.rb 
class SlotsController < ApplicationController 
    def edit 
     @slot = Slot.find params[:id] 
    end 

    def update 
     @slot = Slot.find params[:id] 
     @slot.update slot_params 
    end 

    private 

    def slot_params 
     params.require(:slot).permit(students_attributes: [:present]) 
    end 
end