#258 Token Fields (revised)
The Chosen plugin makes it easy to turn a many-to-many select menu into a searchable token field. Then see how the jQuery Tokeninput field can help with AJAX loading and creating new records.
- Download:
- source codeProject Files in Zip (173 KB)
- mp4Full Size H.264 Video (26.8 MB)
- m4vSmaller H.264 Video (12.3 MB)
- webmFull Size VP8 Video (15.4 MB)
- ogvFull Size Theora Video (28.1 MB)
Resources
Chosen
Gemfile
group :assets do gem 'chosen-rails' end
app/assets/javascripts/application.js
//= require chosen-jquery
app/assets/stylesheets/application.css
*= require chosen
app/assets/javascripts/books.js.coffee
jQuery -> $('#book_author_ids').chosen()
books/_form.html.erb
<div class="field"> <%= f.label :author_ids, "Authors" %><br /> <%= f.collection_select :author_ids, Author.order(:name), :id, :name, {}, {multiple: true} %> </div>
jQuery Tokeninput
app/assets/javascripts/application.js
//= require jquery.tokeninput
app/assets/stylesheets/application.css
*= require token-input-facebook
app/assets/javascripts/books.js.coffee
jQuery -> $('#book_author_tokens').tokenInput '/authors.json' theme: 'facebook' prePopulate: $('#book_author_tokens').data('load')
books/_form.html.erb
<div class="field"> <%= f.label :author_tokens, "Authors" %><br /> <%= f.text_field :author_tokens, data: {load: @book.authors} %> </div>
models/book.rb
attr_accessible :name, :author_tokens attr_reader :author_tokens def author_tokens=(tokens) self.author_ids = Author.ids_from_tokens(tokens) end
authors_controller.rb
def index @authors = Author.order(:name) respond_to do |format| format.html format.json { render json: @authors.tokens(params[:q]) } end end
models/author.rb
def self.tokens(query) authors = where("name like ?", "%#{query}%") if authors.empty? [{id: "<<<#{query}>>>", name: "New: \"#{query}\""}] else authors end end def self.ids_from_tokens(tokens) tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id } tokens.split(',') end