Here is a function from raislcasts.com complex-form-examples about dynamically adding field to form. The function runs with rails 3.1.3 and jquery.
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, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
end
The association is a symbol and has to be. What ‘s the purpose of \"...\" here for #{..}? Removing it causes error.
The purpose is to escape quote characters appearing inside the same type of quote characters to make sure that the string does not end with this character
Examples for appropriate usage