3

我使用軌道4Simple_formacts_as_taggablejQuery的標籤,輸入與Rails4/Simple_form

我試圖實現jQuery Tags Input我的標籤(atcs_as_taggable)。

Tags_input的HTML是:

<input name="tagsinput" class="tagsinput" value="School,Teacher,Colleague" /> 

它轉換在Simple_form:我改變之前進入

<%= f.input :tag_list, input_html: { class: "tagsinput "} %> 

標籤中正確顯示編輯/表單,但新標籤arent保存。

的JS我Tags_input很簡單:

$(".tagsinput").tagsInput({ 
    width: '300px' 
    }); 

我在想什麼?

+0

你解決這個查詢? –

+0

@ rmagnum2002的回答覆蓋了我! –

回答

13

至於我,這個插件是不是你可以使用的最好的。

我會去與

  1. 獲選http://harvesthq.github.io/chosen/
  2. jQuery的Tokeninputhttp://loopj.com/jquery-tokeninput/

以前喜歡第二個,但選擇是一個很棒的插件,現在是我最喜歡的插件。

至於在軌道執行這些:

獲選

的Gemfile

group :assets do 
    gem 'chosen-rails' 
end 

應用程序/資產/ Java腳本/ application.js中

//= require chosen-jquery 

應用程序/資產/樣式表/ application.css

*= require chosen 

應用程序/資產/ Java腳本/ questions.js.coffee

jQuery -> 
    $('#question_tags_ids').chosen() 

問題/ _form.html。ERB

<div class="field"> 
    <%= f.label :tag_ids, "Tags" %><br /> 
    <%= f.collection_select :tag_ids, Tag.order(:name), :id, :name, {}, {multiple: true} %> 
</div> 

jQuery的Tokeninput

應用程序/資產/ Java腳本/ application.js中

//= require jquery.tokeninput 

應用程序/資產/樣式表/ application.css

*= require token-input-facebook 

應用程序/資產/ Java腳本/ questions.js.coffee

jQuery -> 
    $('#question_tag_tokens').tokenInput '/tags.json' 
    theme: 'facebook' 
    prePopulate: $('#question_tag_tokens').data('load') 

問題/ _form.html.erb

<div class="field"> 
    <%= f.label :tag_tokens, "Tags" %><br /> 
    <%= f.text_field :tag_tokens, data: {load: @question.tags} %> 
</div> 

型號/ question.rb

attr_accessible :name, :tag_tokens 
attr_reader :tag_tokens 

def tag_tokens=(tokens) 
    self.tag_ids = Tag.ids_from_tokens(tokens) 
end 

tags_controller.rb

def index 
    @tags = Tag.order(:name) 
    respond_to do |format| 
    format.html 
    format.json { render json: @tags.tokens(params[:q]) } 
    end 
end 

型號/ tag.rb

def self.tokens(query) 
    tags = where("name like ?", "%#{query}%") 
    if tags.empty? 
    [{id: "<<<#{query}>>>", name: "New: \"#{query}\""}] 
    else 
    tags 
    end 
end 

def self.ids_from_tokens(tokens) 
    tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id } 
    tokens.split(',') 
end 
+0

你可以加入我聊天嗎? http://chat.stackoverflow.com/rooms/38054/the-mini-johns-rails-tags-input-room –