如果标签不存在于选定的轨道中,则添加标签

时间:2016-10-07 15:56:25

标签: ruby-on-rails jquery-tokeninput

我已经实现了使用selected-rails和act-as-taggable gems在Rails中为帖子添加标签的功能。我希望通过让用户创建新标签(如果它不存在)来进一步增强功能。

form.html.slim

.form-group.text-center
        = f.label :tag_ids, "Tags"
        = f.collection_select :tag_ids, Tag.order(:name), :id, :name, {}, {multiple: true}

enter image description here

我需要添加一个新标签,如果它不存在的话。

1 个答案:

答案 0 :(得分:2)

好的Selectize.js,Acts_as_Taggable,& SimpleForm:

首先,将您的输入从collection_select更改为普通字符串输入。 Selectize.js会在有逗号的地方将所有值分隔为标记。这种情况发生在幕后,所以当人们添加标签时,它实际上是用您提供的分隔符将长字符串插入数据库。然后,您需要为该字段添加一个ID,以便初始化选择,例如:

<%= f.input :nationalities, as: :string, placeholder: "Nationalities", input_html: { id: 'nationality-input'} %>

然后初始化selectize.js:

#The following line gets all tags ever posted for a user with the context 'nationalities' which we will use as options.
<%=nations = ActsAsTaggleOn::Tagging.includes(:tag).where(context: 'nationalities').uniq.pluck(:id, :name)
$(document).ready(function() {
 $('#nationality-input).selectize({
    delimiter: ',',
    persist: true,
    allowEmptyOption: false,
    options: [
       <% nations.each do |nat| %>
         {text: '<%=nat[1] %>', value: '<%=nat[1]%>' },
       <% end %>
    searchField: 'text',
    create: function(input) {
       return {
          value: input,
          text: input
     }
   } 
});
});

确保正确设置acts_as_taggable并且相应的模型包含它。然后在你的控制器中,用逗号和所有内容保存整个字符串,并允许选择性地在视图上自动重新格式化。