I am using Ryan Bates' Complex Forms Deep Branch, and trying to replicate that example for a form that has two additional nested levels.
SurveyName has many SurveyQuestions, which have many SurveyOptions.
# application_helper (identical to deep branch)
def remove_child_link(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
def add_child_link(name, f, method)
fields = new_child_fields(f, method)
link_to_function(name, h("insert_fields(this, \"#{method}\", \"# {escape_javascript(fields)}\")"))
end
开发者_如何学编程
def new_child_fields(form_builder, method, options = {})
options[:object] ||= form_builder.object.class.reflect_on_association(method).klass.new
options[:partial] ||= method.to_s.singularize
options[:form_builder_local] ||= :f
form_builder.fields_for(method, options[:object], :child_index => "new_#{method}") do |f|
render(:partial => options[:partial], :locals => { options[:form_builder_local] => f })
end
end
# application.js (identical to deep branch)
function insert_fields(link, method, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + method, "g")
$(link).up().insert({
before: content.replace(regexp, new_id)
});
}
function remove_fields(link) {
var hidden_field = $(link).previous("input[type=hidden]");
if (hidden_field) {
hidden_field.value = '1';
}
$(link).up(".fields").hide();
}
In Deep Branch, Project has many tasks, which have many assignments. My _task.html.erb
equivalent is:
<div class="fields">
<%= remove_child_link "remove", f %>
<%= f.fields_for :survey_options do |survey_option_form| %>
<%= render :partial => "survey_option", :locals => { :f => survey_option_form } %>
<% end %>
# the above works
<%= add_child_link "Add Option", f, :survey_options %>
# the above line does NOT work
</div>
I hope I've given enough information. It is mystifying to me that with the same helper code the add_child_link function wouldn't work. Can you see what I'm missing?
You have not added the javascript code in your application.js.
精彩评论