我正在使用 select2 jquery gem。我正在尝试获取与用户类型匹配的主题列表。它没有按预期工作,我花了一整天的时间试图找出原因。我在控制台中不断收到此错误
Uncaught TypeError: Cannot call method 'toUpperCase' of undefined select2.js?body=1:363
Uncaught TypeError: Cannot call method 'localeCompare' of undefined
第二个错误链接到这一行的js文件
return this.text.localeCompare(term) === 0;
有什么我做错了吗?提前致谢。
我的路线:
get '/topic/topic_list' => 'topic#topic_list'
在我的主题控制器中,我有:
def topic_list
@topics = Topic.order(:name)
respond_to do |format|
format.html
format.json { render json: @topics.where('name like ?', "%#{params[:q]}%") }
end
end
主题js文件
$(function () {
$('#story_topic_list').select2({
tags: true,
width: '100%',
tokenSeparators: [","," "],
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
},
multiple: true,
maximumSelectionSize: 5,
formatSelectionTooBig: function (limit) {
return 'You can only add 5 topics'
},
ajax: {
dataType: 'json',
url: '/topic/topic_list.json',
data: function (term, page) {
return { q: term };
},
results: function(data, page) {
return { results: data };
}
}
})
});
在我的表格中,我有
<%= f.label :topic_list %>
<%= f.text_field :topic_list %>
/topic/topic_list.json 也返回这个:
[{"id":2,"name":"app","added_by":null,"cover_id":null,"created_at":"2014-03-23T20:12:24.615+00:00","updated_at":"2014-03-23T20:12:24.615+00:00","count":1},{"id":5,"name":"app tech website","added_by":1,"cover_id":null,"created_at":"2014-03-23T20:23:33.754+00:00","updated_at":"2014-03-23T20:23:33.754+00:00","count":1},{"id":3,"name":"tech","added_by":null,"cover_id":null,"created_at":"2014-03-23T20:12:24.668+00:00","updated_at":"2014-03-23T20:12:24.668+00:00","count":1},{"id":4,"name":"website","added_by":null,"cover_id":null,"created_at":"2014-03-23T20:12:24.677+00:00","updated_at":"2014-03-23T20:12:24.677+00:00","count":1}]