Skip to content

Instantly share code, notes, and snippets.

@richmolj
Created January 6, 2015 20:35
Show Gist options
  • Save richmolj/c3ed4d33a164e5df27b3 to your computer and use it in GitHub Desktop.
Save richmolj/c3ed4d33a164e5df27b3 to your computer and use it in GitHub Desktop.
"Solution"
function remove_fields(link) {
  $(link).prev("input[type=hidden]").val("1");
  $(link).closest(".fields").hide();
}

function add_fields(link, association, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + association, "g")
  $(link).parent().before(content.replace(regexp, new_id));
}
module ApplicationHelper
  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, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment