Unobtrusive dynamic form fields in Rails with jQuery

前端 未结 6 1068
情话喂你
情话喂你 2020-12-12 10:10

I\'m attempting to get over the hurdle of dynamic form fields in Rails -- this appears to be something the framework doesn\'t handle very gracefully. I\'m also using jQuery

6条回答
  •  暖寄归人
    2020-12-12 10:35

    By the way. rails has changed a bit so you can not longer use _delete, now use _destroy.

    def remove_child_link(name, f)
      f.hidden_field(:_destroy) + link_to(name, "javascript:void(0)", :class => "remove_child")
    end
    

    Also I found it easier to just remove html that is for new records... so i do this

    $(function() {
      $('form a.add_child').click(function() {
        var association = $(this).attr('data-association');
        var template = $('#' + association + '_fields_template').html();
        var regexp = new RegExp('new_' + association, 'g');
        var new_id = new Date().getTime();
    
        $(this).parent().before(template.replace(regexp, new_id));
        return false;
      });
    
      $('form a.remove_child').live('click', function() {
        var hidden_field = $(this).prev('input[type=hidden]')[0];
        if(hidden_field) {
          hidden_field.value = '1';
        }
        $(this).parents('.new_fields').remove();
        $(this).parents('.fields').hide();
        return false;
      });
    });
    

提交回复
热议问题