rails nested_forms错误和逻辑

时间:2013-04-02 20:09:05

标签: ruby-on-rails nested-forms

我试图在嵌套表单中添加一些字段。我已经加入了宝石nested_formshttps://github.com/ryanb/nested_form)。

对于我的预建地图,它工作正常,但我无法添加新字段。

我的控制器:

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 gem中完成的....

1 个答案:

答案 0 :(得分: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 %>