【问题标题】:select2, simple_form and acts_as_taggable_onselect2、simple_form 和acts_as_taggable_on
【发布时间】:2017-11-15 08:03:36
【问题描述】:

我正在尝试向模型添加标签。我需要它具有以下功能:

  • 使用 select2 在视图中呈现为标签
  • 用户可以创建自己的标签(即输入新标签,然后输入“空格”或“,”)
  • 提示用户使用现有标签以保持输入一致

即与发布问题时“标签”框在本网站上的工作方式相同!

我已经完成了 99%,但我采取的每一种方法似乎都有一部分不起作用。

这是我的软件版本:

  • select2-rails (3.5.7)
  • simple_form (3.0.1)
  • 作为可标记的 (4.0.0)
  • Rails 4.03

以下代码:正确渲染,但无法在保存前添加新标签,提示现有标签有效

@tags = ActsAsTaggableOn::Tag.all
<%= f.input :tag_list, input_html: { class: 'tags', multiple: true}, collection: @tags, value_method: :name %>

$('.tags').select2({ 

    tokenSeparators: [',', ' '],
    placeholder: "Add your tag here"
});

以下代码:呈现为多行文本框,而不是通过 select2 标记

@tags = ActsAsTaggableOn::Tag.all
<%= f.input :tag_list, input_html: { class: 'tags', multiple: true}, collection: @tags, value_method: :name %>

$('.tags').select2({ 
    tags: true, 
    tokenSeparators: [',', ' '],
    placeholder: "Add your tag here"
});

以下代码:渲染正确,可以添加新标签,但不提示选择现有标签

@tags = ActsAsTaggableOn::Tag.all
<%= f.input :tag_list, input_html: { class: 'tags', multiple: true } %>

$('.tags').select2({ 
    tags: true, 
    tokenSeparators: [',', ' '],
    placeholder: "Add your tag here"
});

【问题讨论】:

    标签: ruby-on-rails-4 jquery-select2 simple-form acts-as-taggable-on


    【解决方案1】:

    对于发现此问题的任何人,我最终都会这样做以使其正常工作。

    @tags = ActsAsTaggableOn::Tag.all.pluck(:name)
    <%= f.input :tag_list, input_html: { class: 'tags', multiple: true, data: {options: @tags} } %>
    
    $('.tags').select2({ 
        tags: $('.tags').data('options'),
        tokenSeparators: [' ', ',']
    }); 
    

    很高兴听到是否有更清洁的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 2013-02-15
      • 2012-01-03
      相关资源
      最近更新 更多