select2 simple_form 并使用远程数据进行初始选择
select2 simple_form and initial selected with remote data
我已经在我的应用程序中使用了 simple_form 和 select2,到目前为止它运行良好。
我有这个代码:
<%= f.association :location_from,
collection: @model.locations,
label_method: :select_label,
value_method: :id,
include_blank: false,
label: 'From Location',
class: 'select form-control'
%>
和我的 javascript:
$('#pipeline_segment_location_from_id').select2({
placeholder: 'Select a From Location...',
allowClear: false,
multiple: false,
ajax: {
url: '/locations/select.json',
dataType: 'json',
data: function(params) {
return {
'q[loc_cont]': params.term,
page: params.page
};
},
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
text: item.text,
id: item.id
};
})
};
}
}
});
下拉菜单按预期工作(即 ajax 等)。记录保存等。问题是当我再次编辑记录时 select 是空白的,相关记录没有加载到 select。我想我在这里遗漏了一些基本的东西,但我似乎无法弄清楚。
更新
我在这方面工作到很晚。两个问题——我传递的 @model.locations 是从另一个不相关的 select 复制而来的,它预加载了错误的选项。我需要做的就是根据下面接受的答案添加 selected:
。
<%= f.association :location_from,
selected: @model.location_from_id,
label_method: :select_label,
value_method: :id,
include_blank: false,
label: 'From Location',
class: 'select form-control'
%>
您可以传递一个额外的参数selected: some_ids
。喜欢
= f.association :location_from, collection: @model.locations, selected: @record.map(&:location_id), ....
我已经在我的应用程序中使用了 simple_form 和 select2,到目前为止它运行良好。
我有这个代码:
<%= f.association :location_from,
collection: @model.locations,
label_method: :select_label,
value_method: :id,
include_blank: false,
label: 'From Location',
class: 'select form-control'
%>
和我的 javascript:
$('#pipeline_segment_location_from_id').select2({
placeholder: 'Select a From Location...',
allowClear: false,
multiple: false,
ajax: {
url: '/locations/select.json',
dataType: 'json',
data: function(params) {
return {
'q[loc_cont]': params.term,
page: params.page
};
},
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
text: item.text,
id: item.id
};
})
};
}
}
});
下拉菜单按预期工作(即 ajax 等)。记录保存等。问题是当我再次编辑记录时 select 是空白的,相关记录没有加载到 select。我想我在这里遗漏了一些基本的东西,但我似乎无法弄清楚。
更新
我在这方面工作到很晚。两个问题——我传递的 @model.locations 是从另一个不相关的 select 复制而来的,它预加载了错误的选项。我需要做的就是根据下面接受的答案添加 selected:
。
<%= f.association :location_from,
selected: @model.location_from_id,
label_method: :select_label,
value_method: :id,
include_blank: false,
label: 'From Location',
class: 'select form-control'
%>
您可以传递一个额外的参数selected: some_ids
。喜欢
= f.association :location_from, collection: @model.locations, selected: @record.map(&:location_id), ....