【发布时间】:2011-07-13 04:34:09
【问题描述】:
这就是您如何使用 jQuery Tokeninput 和 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 => :tags
Application.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,您也不必更改表单。
以下是关于您为什么需要这样做的 2 个问题:
我有以下Tag:{"id":1,"name":"Food"}。当我保存Product,标记为"Food" 时,它应该在搜索并找到名称"Food" 时保存为ID: 1。目前,它使用引用"Food" ID 的新ID 保存新的Tag,即{"id":19,"name":"1"}。相反,它应该查找 ID、显示名称并执行 find_or_create_by,因此它不会创建新的 Tag。
问题 2(已解决)
当我通过<%= @product.tag_list %> 去products/show 查看标签时。名称显示为“Tags: 1”,而实际上应该是“Tags: Food”。
如何解决这些问题?
【问题讨论】:
-
您能否从
rake routes的输出中添加相关部分。似乎您因路线而面临一些问题。 -
我能想到的关于我的路线的唯一相关部分是 new_product GET /products/new(.:format) {:action=>"new", :controller=>"products"},我编辑了我的答案并包含了我所有的产品路线。
-
你能发布你的控制器方法来接受来自标签表单的数据吗?
-
我没有标签表单吗?你的意思是我的 ProductsController 新方法和创建方法,如果是这样,我会将它们发布到。标记方法已经启动。
-
问题是采取输入将 id 列表提交回服务器而不是名称,并且看起来像 act-as-taggable 直接与名称一起使用。查看已编辑的
tags回答中的操作。
标签: ruby-on-rails ruby ruby-on-rails-3 autocomplete acts-as-taggable-on