Rails选择ajax标签



我使用的是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}]

select2不知道要使用传回的数据中的哪个字段。假设是name字段,单独添加这个函数(不在select2中):

function format(item) { return item.name; }

和以下两个选项来选择:

formatSelection: format,
formatResult: format

相关内容

  • 没有找到相关文章

最新更新