我将nested_form_fields
用于嵌套字段,并将select2
问题是,当我添加另一行嵌套字段时,先前选择的值消失了,并且该值无法再次选择。
_form.htmt.haml
= f.nested_fields_for :expense_accounts do |ff|
.row.mt-2
.col-md-2
.plain-select
= ff.select :expense_type, '', {}, class: "form-control select_expense_types"
.col-md-2
= ff.text_area :description, class: 'form-control', cols: "2", rows: "2"
.col-md-2
= ff.select :status, Expense.statuses.map { |key, value| [key.titleize, key] } , {class: "form-control" , required: true}
.col-md-2
= ff.text_field :amount, class: 'form-control'
.col-md-2
.col-md-2
= ff.remove_nested_fields_link 'Remove'
%br
= f.add_nested_fields_link :expense_accounts, 'Add row', class: 'btn btn-primary add_row'
- content_for :scripts do
:javascript
set_expense_type_select('.select_expense_types', "Please select");
$('.add_row').on('click', function(){
setTimeout(
function() {
set_expense_type_select('.select_expense_types', "Please select");
},
500);
})
select_autocomplete.js
var set_expense_type_select = function(selector, place_holder){
if ($(selector).length > 0) {
$(selector).select2({
ajax: {
url: "/api/select_searches/find_expense_type",
dataType: 'json',
delay: 250,
data: function (params) {
return {
// per_page: 10,
q: params.term//, // search term
// page: params.page
};
},
processResults: function (data, params) {
// params.page = params.page || 1;
return {
results: data
};
},
cache: true
},
language: {
noResults: function() {return "No results <a class='pull-right header-btn hidden-mobile' data-toggle='modal' data-target='#new-expense-type' href='#'>Add New</a>"; }
},
placeholder: place_holder,
escapeMarkup: function (markup) { return markup; },
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
}
}
每次添加新行时,以前的expense_type
都会被清除,并且所选值无法再次选择
你有什么主意吗? 任何帮助将不胜感激。