3

我已经实现了这篇文章中概述的框架:How to use jquery-Tokeninput and Acts-as-taggable-on有一些困难。就预先填充适当的主题和 ajax 搜索而言,这是有效的,但是当我输入一个新标签时,它会在文本区域失去焦点时立即被删除。我不确定我做错了什么。这是我的一些相关代码:

用户模型(做标记):

class User < ActiveRecord::Base
[...]
# tagging
acts_as_tagger

商品型号(接受标签):

class Item < ActiveRecord::Base
attr_accessible :title, :tag_list

#tagging functionality
acts_as_taggable_on :tags

物品控制器:

def tags 
@tags = ActsAsTaggableOn::Tag.where("tags.name LIKE ?", "%#{params[:q]}%") 
 respond_to do |format|
  format.json { render :json => @tags.collect{|t| {:id => t.name, :name => t.name }}}
 end
end

在我的部分表格上:

<%= f.input :tag_list, :label => "Tags", :input_html => { :class => "text_field short", "data-pre" => @item.tags.map(&:attributes).to_json }, :hint  => "separate tags by a space"  %>

我的路线:

get "items/tags" => "items#tags", :as => :tags
resources :items 

[差不多好了!!!]

表单上的 js [注意:元素的 id 是动态分配的]:

<script type="text/javascript">
$(function() {
  $("#item_tag_list").tokenInput("/art_items/tags", {
    prePopulate:       $("#item_tag_list").data("pre"),
    preventDuplicates: true,
    crossDomain: false,
    theme: "facebook"
  });
});
</script>
4

1 回答 1

3

如果您仍想使用 Jquery TokenInput 并添加标签,则可以使用不同的方法。

1.这实际上来自我的同一个问题;最新答案:如何使用 jquery-Tokeninput 和 Acts-as-taggable-on

这可以进入您的控制器。

 def tags
    query = params[:q]
    if query[-1,1] == " "
      query = query.gsub(" ", "")
      Tag.find_or_create_by_name(query)
    end

    #Do the search in memory for better performance

    @tags = ActsAsTaggableOn::Tag.all
    @tags = @tags.select { |v| v.name =~ /#{query}/i }
    respond_to do |format|
      format.json{ render :json => @tags.map(&:attributes) }
    end
  end

This will create the tag, whenever the space bar is hit.

You could then add this search setting in the jquery script:

noResultsText: 'No result, hit space to create a new tag',

It's a little dirty but it works for me.

2.看看这家伙的方法:https ://github.com/vdepizzol/jquery-tokeninput

他做了一个自定义输入能力:

$(function() {
  $("#book_author_tokens").tokenInput("/authors.json", {
    crossDomain: false,
    prePopulate: $("#book_author_tokens").data("pre"),
    theme: "facebook",
    allowCustomEntry: true
  });
});

3.不确定这个,但它可能会有所帮助:Rails : Using jquery tokeninput (railscast #258) to create new entries


4. 这个似乎也是合法的:https ://github.com/loopj/jquery-tokeninput/pull/219

我个人喜欢第一个,似乎最容易获得和安装。

于 2011-12-09T02:22:24.957 回答