Lea*_*RoR 14 ruby autocomplete ruby-on-rails acts-as-taggable-on ruby-on-rails-3
这是您使用jQuery Tokeninput和ActsAsTaggableOn自动完成的方式.
在我的情况下,我使用嵌套的形式,但它不重要.以下所有内容都是有效的代码.
产品型号:
attr_accessible :tag_list # i am using the regular :tag_list
acts_as_taggable_on :tags # Tagging products
Run Code Online (Sandbox Code Playgroud)
产品控制器:
#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
Run Code Online (Sandbox Code Playgroud)
路线:
# It has to find the tags.json or in my case /products/tags.json
get "products/tags" => "products#tags", :as => :tags
Run Code Online (Sandbox Code Playgroud)
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
});
});
Run Code Online (Sandbox Code Playgroud)
形成:
<%= p.text_field :tag_list,
:id => "product_tags",
"data-pre" => @product.tags.map(&:attributes).to_json %>
Run Code Online (Sandbox Code Playgroud)
必须有这条线:
format.json { render :json => @tags.collect{|t| {:id => t.name, :name => t.name }}}
Run Code Online (Sandbox Code Playgroud)
注意 - 你也可以@tags.map在这里使用,你也不必改变形式.
以下是您需要执行此操作的两个问题:
我有以下几点Tag:{"id":1,"name":"Food"}.当我保存Product标记时"Food",它应该保存为ID: 1搜索时找到的名称"Food".目前,它Tag使用引用"Food"ID 的新ID 保存新的,即{"id":19,"name":"1"}.相反,它应该是找到ID,显示名称,并且这样做find_or_create_by不会创建新的Tag.
当我去看products/show标签时<%= @product.tag_list %>.名称显示为" Tags:1 ",当它真的应该是" Tags:Food "时.
我该如何解决这些问题?
您应该在您的路径中定义一个routes.rb应该处理products/tags路径的路由。您可以将其定义为:
get "products/tags" => "products#tags", :as => :tags
Run Code Online (Sandbox Code Playgroud)
因此应该给你一个tags_path应该评估为/products/tags. 这应该可以消除您在问题中提到的错误。请务必定义之前添加这条路线resources :product在routes.rb
现在到act-as-taggable-on,我没有使用过这个 gem,但你应该看看方法all_tag_counts 文档。您的ProductsController#tags方法需要对以下几行进行一些更改。我不确定它是否确切需要什么,因为我使用 Mongoid 并且无法对其进行测试。
def tags
@tags = Product.all_tag_counts.(:conditions => ["#{ActsAsTaggableOn::Tag.table_name}.name LIKE ?", "%#{params[:q]}%"])
respond_to do |format|
format.json { render :json => @tags.collect{|t| {:id => t.name, :name => t.name } }
end
end
Run Code Online (Sandbox Code Playgroud)