I am having trouble with my nested form. I am using Ryan Bates’ code. Gemfile snippet:
gem “nested_form”, :git => ‘https://github.com/ryanb/nested_form.git’
The problem is that when I try to use *link_to_add* I get a new item which looks normal, but it doesn’t work because it gets a new index of 0 instead of a ‘random’ index based on the current time that the nested_form.js is supposed to generate. Every item that I add gets the same 0 index. So of the effect is I cannot add a new item (or only the last new one is saved, depending on the original state of the model).
The behavior is the same with a new parent object and when editing a parent object.
I am pretty sure I am doing something wrong since I was able to do a simple new app that works. But I can’t figure out what is wrong with my real app.
The nested_form.js generated for my (working) test app and my (not working) real app are identical. So I don’t think there is a problem with a version difference.
I used Firebug to step through the code in nested_form.js but was not able to figure out why it was generating a 0 index there.
My parent model has this:
class Course < ActiveRecord::Base
accepts_nested_attributes_for :levels, :allow_destroy => true
has_many :levels, :dependent => :destroy, :order => :depth
My form is instantiated like this:
<%= nested_form_for(@course) do |f| %>
The part with the nested object is like this:
<%= f.fields_for :levels do |builder| %>
<tr>
<td><%= builder.text_field :name %></td>
<td><%= image_tag(builder.object.icon) unless (builder.object.icon.nil?) %></td>
<td><%= builder.link_to_remove "Remove" %></td>
</tr>
<% end %>
<tr><td><%= f.link_to_add "Add a level", :levels %></td></tr>
I don’t see any difference between my code and my working example (or other examples I’ve seen).
Does anyone have any ideas?
UPDATE:
After trying to debug this some more in Firebug I realized the ‘blueprint’ used by the addFields function in nested_form.js was being changed inside the addFields method and that’s why it wasn’t putting in the generated index (that block was being bypassed in my test app). So I overrode the block where this happens by changing:
if (context) {
to:
if (false)
This seems to fix my symptom from preliminary testing but I sense that in some contexts (NPI) this may have broken something else (maybe with multiple levels of nesting?).
Although I feel somewhat silly I think this is something that might happen to someone else (and I did say in my question I was probably doing something ‘wrong’).
What I was doing ‘wrong’ was I was using fieldsets to segregate areas of my form. And I was giving the fieldsets the class ‘fields’. Not good. Conflicts with classes of the form generator.