Rails + javascript oddity

Status
Not open for further replies.

Zaskar

Ars Praefectus
3,347
Subscriptor
I'm at a loss why this is happening, everyone around me is tossing their hands up. So I'll put it to the hive mind. This is some serious simple shit. Why it's causing angst is part of the problem in itself.

The problem. Building an app that needs to not require gems beyond rails and ORM driver. This would be solved with cocoon but the delivery rule....

Building forms on the fly that have has_many associations, needs a wee bit of mark up, javascript and logic to pull off here are those bits.

Inside the application helper we have a method for building the button on the form to add a copy of the form snippet to the markup.

Code:
  def add_child_button(name, association,target)
    content_tag(:button,name,
      :class => "add_child",
      :"data-association" => association,
      :target => target)
  end

Then we have a bit of jquery to handle the on_click

Code:
$('.add_child').click(function() {

  var association = $(this).attr('data-association');
  var target = $(this).attr('target');
  var regexp = new RegExp('new_' + association, 'g');
  var new_id = new Date().getTime();
  var Dest = (target == '') ? $(this).parent() : $('#'+target);
  console.log(Dest);
  Dest.append(window[association+'_fields'].replace(regexp, new_id));
  return false;
});

The markup is virtually identical between the two forms i'm using this on. One works as expected, the other submits the parent form.

any insight?
 

Zaskar

Ars Praefectus
3,347
Subscriptor
Quick update so if someone runs into this themselves....

I changed the javascript to this:

Code:
jQuery(function() {
  $(document).on('click', '.remove-nested-form', function(event) {
    $(this).prev('input[type=hidden]').val('1');
    $(this).closest('fieldset').remove();
    return event.preventDefault();
  });
  return $(document).on('click', '.add-nested-form', function(event) {
    var regexp, time;
    time = new Date().getTime();
    regexp = new RegExp($(this).data('id'), 'g');
    $(this).before($(this).data('fields').replace(regexp, time));
    return event.preventDefault();
  });
});

and the rails helper to this:

Code:
  def link_to_add_form(name, f, association)
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    fields = f.fields_for(association, new_object, child_index: id) do |form|
      render(association.to_s.singularize + "_fields", f: form)
    end
    content_tag(:button, name,
                :type => 'button',
                :class => 'add-nested-form',
                :"data-association" => association,
                :data => { id: id, fields: fields.gsub("\n", "")})
  end

This leaves me with the problem of the same id in the form for each addition. This ended up not a big deal, rails somehow figures it out.
 
Status
Not open for further replies.