这就是如何在jQuery托肯输入和ActsAsTaggableOn中使用自动完成的方法。
在我的情况下,我使用的是嵌套形式,但这不重要。下面的所有内容都是工作的代码。
代码
产品模型:
attr_accessible :tag_list # i am using the regular :tag_list
acts_as_taggable_on :tags # Tagging products产品财务主任:
#1. Define the tags path
#2. Searches ActsAsTaggable::Tag Model look for :name in the created table.
#3. it finds the tags.json path and whats on my form.
#4. it is detecting the attribute which is :name for your tags.
def tags
@tags = ActsAsTaggableOn::Tag.where("tags.name LIKE ?", "%#{params[:q]}%")
respond_to do |format|
format.json { render :json => @tags.map{|t| {:id => t.name, :name => t.name }}}
end
end路线:
# It has to find the tags.json or in my case /products/tags.json
get "products/tags" => "products#tags", :as => :tagsApplication.js:
$(function() {
$("#product_tags").tokenInput("/products/tags.json", {
prePopulate: $("#product_tags").data("pre"),
preventDuplicates: true,
noResultsText: "No results, needs to be created.",
animateDropdown: false
});
});表格:
<%= p.text_field :tag_list,
:id => "product_tags",
"data-pre" => @product.tags.map(&:attributes).to_json %>问题1(已解决)
必须有线路:
format.json { render :json => @tags.collect{|t| {:id => t.name, :name => t.name }}}注:您也可以在这里使用@tags.map,您也不必更改表单。
以下是您为什么需要这样做的两个问题:
我有以下Tag:{"id":1,"name":"Food"}。当我保存一个标记为Product的"Food"时,当它搜索并找到名称"Food"时,它应该保存为ID: 1。目前,它使用引用"Food" ID (即{"id":19,"name":"1"} )的新ID保存一个新的{"id":19,"name":"1"}。相反,它应该找到ID,显示名称,并执行find_or_create_by,这样它就不会创建新的Tag。
问题2(已解决)
当我去products/show通过执行<%= @product.tag_list %>来查看标记时。该名称显示为“标记: 1",而它实际上应该是”标签:食品“。
我怎样才能解决这些问题?
发布于 2011-10-15 08:59:03
Application.js代码中有一个bug。在"/products/tags.json“之后有一个额外的)。移除多余的)。守则应是:
$("#product_tags").tokenInput("/products/tags.json", {
prePopulate: $("#product_tags").data("pre"),
preventDuplicates: true,
noResultsText: "No results, needs to be created.",
animateDropdown: false
});发布于 2011-11-23 00:11:09
小附加:
如果要动态创建标记,可以在控制器中这样做:
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这将创建标签,每当空格键被击中。
然后,可以在jquery脚本中添加此搜索设置:
noResultsText: 'No result, hit space to create a new tag',有点脏但对我有用。
发布于 2011-07-13 17:16:14
我不知道这是否是您的全部错误,但您没有击中正确的tokenInput插件的网址。
这
$("#product_tag_list").tokenInput("/products/tags.json"), {应该是
$("#product_tag_list").tokenInput("/products.json"), {就像我说的,我不知道这是否是你唯一的问题,但是如果你改变了这个,它会起作用吗?
编辑:
我从未使用过ActsAsTaggableOn。它是否创建了一个供您使用的Tag模型?
从github上的外观来看,如果您想查询所有标记,您可能必须使用它的名称空间,而不仅仅是Tag,意思是ActsAsTaggableOn::Tag。例如,您可以看到他们如何在某些Tag中直接访问规格。
https://stackoverflow.com/questions/6674127
复制相似问题