Topic: Rails Nested Model Form (196 & 197): Add nested model fields
Hi all,
I'm following a Railscasts #196 & 197 from Jan 2010 (http://railscasts.com/episodes/197-nest orm-part-2). The cast, like all railcasts I've seen, is well done.
I'm implementing Project lists that has_many Items.
The code to dynamically add Item fields is not working, but I am able to hide/remove fields with js OK.
#views/projects/_form.html.erb
<%= form_for(@project) do |f| %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<% f.fields_for :items do |builder| %>
<%= render "item_fields", :f => builder %>
<% end %>
<p><%= link_to_add_fields "+item", f, :items %></p>
<div class="actions"><%= f.submit %></div>
<% end %>#views/projects/_item_fields.html.erb
<div class="fields">
<p>
<%= f.label :name, "item" %>
<%= link_to_remove_fields "remove", f %><br />
<%= f.text_field :name %>
</p>
</div>#helpers/application_helper.rb
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end#public/javascripts/application.js
function remove_fields(link) {
$(link).previous("input[type=hidden]").value = "1";
$(link).up(".fields").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).up().insert({
before: content.replace(regexp, new_id)
});
}The original code is available at https://github.com/ryanb/railscasts-epi surveysays
The difference in the implementation is that my code only has 1 layer (Project / Item). The tutorial has more nesting (Survey / Question + Answer).
What do I need to change in the javascript or other parts to make the add new Item functionality work?
Thank you