これは、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
アプリケーション.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"
する必要があります。現在、ID を参照する新しい ID を持つ新しい を保存します。代わりに、ID を検索し、名前を表示し、新しい を作成しないようにする必要があります。ID: 1
"Food"
Tag
"Food"
{"id":19,"name":"1"}
find_or_create_by
Tag
問題2(解決済み)
products/show
を実行してタグを見に行くと<%= @product.tag_list %>
。名前は「Tags: 1」と表示されますが、実際には「Tags: Food」である必要があります。
これらの問題を解決するにはどうすればよいですか?