Skip to content
This repository was archived by the owner on Dec 12, 2021. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions lib/generators/nested_form/templates/jquery_nested_form.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ jQuery(function($) {
content = content.replace(regexp, "new_" + new_id);

var field = $(content).insertBefore(this);
check_maximum();
$(this).closest("form").trigger({type: 'nested:fieldAdded', field: field});
return false;
});
Expand All @@ -45,7 +46,18 @@ jQuery(function($) {
hidden_field.value = '1';
}
$(this).closest('.fields').hide();
check_maximum();
$(this).closest("form").trigger('nested:fieldRemoved');
return false;
});

function check_maximum() {
$('form a.add_nested_fields').each(function(){
var assoc = $(this).attr('data-association'); // Name of child
var maximum = $(this).attr('data-maximum'); // Maximum # of children
$('.' + assoc+':visible').length >= maximum ? $(this).hide() : $(this).show();
});
}

check_maximum();
});
10 changes: 9 additions & 1 deletion lib/nested_form/builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ def link_to_add(*args, &block)
association = args.pop
options[:class] = [options[:class], "add_nested_fields"].compact.join(" ")
options["data-association"] = association
validators = self.object.class.validators_on(association)
unless validators.empty?
length_validator = validators.select {|item| item.class == ActiveModel::Validations::LengthValidator}.first
unless length_validator.nil?
maximum = length_validator.options[:maximum]
options["data-maximum"] = maximum
end
end
args << (options.delete(:href) || "javascript:void(0)")
args << options
@fields ||= {}
Expand Down Expand Up @@ -57,7 +65,7 @@ def fields_for_with_nested_attributes(association_name, args, block)
end

def fields_for_nested_model(name, object, options, block)
output = '<div class="fields">'.html_safe
output = "<div class=\"fields #{object.class.name.underscore.pluralize}\">".html_safe
output << super
output.safe_concat('</div>')
output
Expand Down