简体   繁体   English

如果标签不存在于已选择的轨道中,则添加一个标签

[英]Adding a tag if it doesn't exist in rails chosen rails

I have implemented the functionality of adding tags to a post in Rails using chosen-rails and acts-as-taggable gems. 我已经实现了使用选定的Rails和行为可标记的gem将标记添加到Rails中的帖子的功能。 I want to further enhance the functionality by making user to create new tag if it doesn't exist. 我想通过使用户创建不存在的新标签来进一步增强功能。

form.html.slim form.html.slim

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

在此处输入图片说明

I need to add a new tag if it doesn't exist. 如果不存在,我需要添加一个新标签。

Ok with Selectize.js, Acts_as_Taggable, & SimpleForm: 可以使用Selectize.js,Acts_as_Taggable和SimpleForm:

Firstly, change your input from collection_select to a normal string input. 首先,将输入从collection_select更改为普通字符串输入。 Selectize.js will separate all of the values into tags anywhere there is a comma. Selectize.js会将所有值分隔为标记,只要有逗号即可。 This happens behind the scenes so as people add tags, it's actually inserting a long string into your database with whatever delimiter you supply. 这是在后台发生的,因此当人们添加标签时,实际上是使用您提供的任何定界符将长字符串插入数据库。 Then you need to add an id to that field so you can initialize selectize such as: 然后,您需要向该字段添加一个ID,以便可以初始化selectize,例如:

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

Then initialize selectize.js: 然后初始化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
     }
   } 
});
});

Make sure you have acts_as_taggable setup properly and that the corresponding model includes it. 确保正确设置了act_as_taggable设置,并且相应的模型包括它。 Then in your controller just save the whole string with commas and all and allow selectize to reformat it on views automagically. 然后在您的控制器中,只需将整个字符串保存为逗号和所有内容,然后允许select自动在视图上重新设置其格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM