我有一个父模型和子模型。
我想强制要求在创建新父项时至少创建一个子项。
我使用的是nested_form gem,目前正在使用此脚本来限制每条记录添加的子项数。
$(function() {
var fieldsCount,
maxFieldsCount = 4,
$addLink = $('a.add_nested_fields');
function toggleAddLink() {
$addLink.toggle(fieldsCount <= maxFieldsCount)
}
$(document).on('nested:fieldAdded', function() {
fieldsCount += 1;
toggleAddLink();
});
$(document).on('nested:fieldRemoved', function() {
fieldsCount -= 1;
toggleAddLink();
});
// count existing nested fields after page was loaded
fieldsCount = $('form .fields').length;
toggleAddLink();
})
我还有办法包括一个&#34;最小值&#34;需求?让我们说(1)孩子?基本上删除&#34;删除链接&#34;如果只有(1)嵌套形式可见。
答案 0 :(得分:0)
以下是我通过根据计数删除“删除”链接确定至少显示一个字段的代码
$(function() {
var fieldsCount,
maxFieldsCount = 2,
$addLink = $('a.add_nested_fields');
var mfieldsCount,
minFieldsCount = 0, // placed at 0 because first object is auto built from controller
$removeLink = $('a.remove_nested_fields');
function toggleAddLink() {
$addLink.toggle(fieldsCount <= maxFieldsCount)
}
function toggleRemoveLink() {
$removeLink.toggle(mfieldsCount <= minFieldsCount)
}
$(document).on('nested:fieldAdded', function() {
fieldsCount += 1;
toggleAddLink();
});
$(document).on('nested:fieldRemoved', function() {
fieldsCount -= 1;
toggleAddLink();
});
$(document).on('nested:fieldRemoved', function() {
mfieldsCount -= 0;
toggleRemoveLink();
});
// count existing nested fields after page was loaded
fieldsCount = $('form .fields').length;
toggleAddLink();
mfieldsCount = $('form .fields').length;
toggleRemoveLink();
})
答案 1 :(得分:0)
您可以在父级的控制器中调用构建方法new action。 因此,当您转到父/新时,您将创建一个孩子。就是这样: @ parent.children.build