2012-12-10 26 views
1

不工作我也跟着https://github.com/ryanb/nested_form的link_to _remove是工作,但在link_to_add鋼軌nested_form 3

刪除功能工作,但加場不工作。

在我的模型中,我正確接受了嵌套屬性。我有分部,有很多部門。

在division.rb

class Division < ActiveRecord::Base 
    attr_accessible :name, :departments_attributes 
    has_many :departments, :dependent => :destroy 
    accepts_nested_attributes_for :departments, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true 

end 

在department.rb

class Department < ActiveRecord::Base 
    attr_accessible :division_id, :name 
    belongs_to :division 
    belongs_to :user 
end 

部門所屬部門,其是正確的。

在我divisions_controller.rb

我的新方法,工程完全按照瑞安B的例子:https://github.com/ryanb/complex-form-examples/tree/nested_form

def new 
    @division = Division.new 
    @division.departments.build 
    end 

另外,我要求我的application.js

//= require nested_form 

nested_form內nested_form.js .js:

jQuery(function($) { 
    $('form a.add_nested_fields').live('click', function() { 
    // Setup 
    var assoc = $(this).attr('data-association');   // Name of child 
    var content = $('#' + assoc + '_fields_blueprint').html(); // Fields template 

    // Make the context correct by replacing new_<parents> with the generated ID 
    // of each of the parent objects 
    var context = ($(this).closest('.fields').find('input:first').attr('name') || '').replace(new RegExp('\[[a-z]+\]$'), ''); 

    // context will be something like this for a brand new form: 
    // project[tasks_attributes][new_1255929127459][assignments_attributes][new_1255929128105] 
    // or for an edit form: 
    // project[tasks_attributes][0][assignments_attributes][1] 
    if(context) { 
     var parent_names = context.match(/[a-z_]+_attributes/g) || []; 
     var parent_ids = context.match(/(new_)?[0-9]+/g) || []; 

     for(i = 0; i < parent_names.length; i++) { 
     if(parent_ids[i]) { 
      content = content.replace(
      new RegExp('(_' + parent_names[i] + ')_.+?_', 'g'), 
      '$1_' + parent_ids[i] + '_'); 

      content = content.replace(
      new RegExp('(\\[' + parent_names[i] + '\\])\\[.+?\\]', 'g'), 
      '$1[' + parent_ids[i] + ']'); 
     } 
     } 
    } 

    // Make a unique ID for the new child 
    var regexp = new RegExp('new_' + assoc, 'g'); 
    var new_id = new Date().getTime(); 
    content  = content.replace(regexp, "new_" + new_id); 

    $(this).before(content); 
    $(this).closest("form").trigger('nested:fieldAdded'); 
    return false; 
    }); 

    $('form a.remove_nested_fields').live('click', function() { 
    var hidden_field = $(this).prev('input[type=hidden]')[0]; 
    if(hidden_field) { 
     hidden_field.value = '1'; 
    } 
    $(this).closest('.fields').hide(); 
    $(this).closest("form").trigger('nested:fieldRemoved'); 
    return false; 
    }); 
}); 

我沒有更改nested_form.js中的某些內容,因爲我從複雜樣本庫中複製了它,所以這是默認值。

任何解決方法都會很好。由於

回答