2013-04-02 116 views
0

我試圖添加一些字段到我的嵌套窗體。我已經包含了寶石nested_formshttps://github.com/ryanb/nested_form)。rails nested_forms錯誤和邏輯

對於我的預建地圖,它工作正常,但我不能添加新的字段。

我的控制器:

def new 
    @people = Person.all 
    @vehicles = Vehicle.all 
    @roles = Role.all 
    @pratice_people = [] 
    @people.each do |a| 
    if a.at1 == true 
     @pratice_people << a 
    end 
    end 
    @practice = Practice.new 
    @pratice_people.count.times { @practice.uebung_maps.build } 
    render action: "new" 
end 

和我的形式:

<% @runs = 0 %> 
<%= f.fields_for :uebung_maps do |map| %> 
    <tr> 
    <%= map.hidden_field :role_id, :id => "role_id_#{@runs}" %> 
    <%= map.hidden_field :vehicle_id, :id => "vehicle_id_#{@runs}" %> 
    <%= map.hidden_field :person_id , :value => @pratice_people[@runs].id %><br/> 
    <td><%= @pratice_people[@runs].name %></td> 
    <td><%= map.select :role_id, options_from_collection_for_select(@roles, :id, :name), :include_blank => true %></td> 
    <td><%= map.select :vehicle_id, options_from_collection_for_select(@vehicles, :id, :name), :include_blank => true %></td> 
    <td><%= map.text_field :time %></td> 
    </tr> 
    <% @runs += 1 %> 
<% end %> 

<%= f.link_to_add "+" , :uebung_maps %> 

,如果我嘗試訪問該頁面時,我得到以下錯誤報告

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id 

我必須(或如何)創建一個邏輯重新運行Practice.uebung_maps.build?,因爲我認爲這是在nested_forms寶石....

+1

'@pratice_people [@runs]''是nil' –

+0

沒關係啊..我會試試這個:) – HappyHacking

+0

好吧,我」我現在改變表單,詢問@pratice_people [@runs] .nil?和表單現在工作,但如果我點擊鏈接什麼都沒有發生......我必須在這裏添加另一個邏輯? – HappyHacking

回答

1

首先,確保模型創建正確。

class Practice < ActiveRecord::Base 
    has_many :uebung_maps 
    accepts_nested_attributes_for :uebung_maps 
end 

class UebungMap < ActiveRecord::Base 

end 

其次,確保form_for正確嵌套

<%= nested_form_for @practice do |f| %> 
    <%= f.fields_for :uebung_maps do |uebung_maps_form| %> 
    <%= uebung_maps_form.text_field :time %> 
    <% end %> 
    <p><%= f.link_to_add "+", :uebung_maps %></p> 
<% end %> 
+0

這就是我所擁有的!我是否需要編寫自己的ajax方法來構建添加新的方法? – HappyHacking

+0

因爲如果我記住它,什麼都沒有發生。在firbug控制檯或任何其他地方沒有錯誤... – HappyHacking