【问题标题】:Rails select2 ajax tagsRails select2 ajax标签
【发布时间】:2014-05-01 02:50:27
【问题描述】:

我正在使用 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}]

【问题讨论】:

    标签: jquery ruby-on-rails jquery-select2 select2-rails


    【解决方案1】:

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

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

    还有以下两个选项供选择:

    formatSelection: format,
    formatResult: format
    

    【讨论】:

    • 如果您仍然收到 localeCompare 错误,您可能需要将 this.text.localeCompare(term) 更改为 this.name.localeCompare(term)
    • 我看到你也是一个 Rails 人,你知道我怎样才能让标签在编辑操作中保持不变吗?我将 topic_list 作为 attr_reader 允许在表单上调用它。
    • 非常感谢您的帮助。我永远不会得到那个。
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    相关资源
    最近更新 更多