#258 Token Fields
With the jQuery Tokeninput plugin it is easy to add an autocompleting list of entries for a many-to-many association.
- Download:
- source codeProject Files in Zip (144 KB)
- mp4Full Size H.264 Video (23.9 MB)
- m4vSmaller H.264 Video (13.7 MB)
- webmFull Size VP8 Video (29.9 MB)
- ogvFull Size Theora Video (29.8 MB)
There is a newer version of this episode, see the revised episode.
Resources
bash
bundle
rails g jquery:install
bundle rails g jquery:install
Gemfile
gem "jquery-rails"
gem "jquery-rails"
models/book.rb
class Book < ActiveRecord::Base
attr_accessible :name, :author_tokens
has_many :authorships
has_many :authors, :through => :authorships
attr_reader :author_tokens
def author_tokens=(ids)
self.author_ids = ids.split(",")
end
end
class Book < ActiveRecord::Base attr_accessible :name, :author_tokens has_many :authorships has_many :authors, :through => :authorships attr_reader :author_tokens def author_tokens=(ids) self.author_ids = ids.split(",") end end
authors_controller.rb
def index
@authors = Author.where("name like ?", "%#{params[:q]}%")
respond_to do |format|
format.html
format.json { render :json => @authors.map(&:attributes) }
end
end
def index @authors = Author.where("name like ?", "%#{params[:q]}%") respond_to do |format| format.html format.json { render :json => @authors.map(&:attributes) } end end
layouts/application.html.erb
<%= stylesheet_link_tag "application", "token-input-facebook" %>
<%= javascript_include_tag :defaults, "jquery.tokeninput" %>
<%= stylesheet_link_tag "application", "token-input-facebook" %> <%= javascript_include_tag :defaults, "jquery.tokeninput" %>
books/_form.html.erb
<p>
<%= f.label :author_tokens, "Authors" %><br />
<%= f.text_field :author_tokens, "data-pre" => @book.authors.map(&:attributes).to_json %>
</p>
<p> <%= f.label :author_tokens, "Authors" %><br /> <%= f.text_field :author_tokens, "data-pre" => @book.authors.map(&:attributes).to_json %> </p>
application.js
$(function() {
$("#book_author_tokens").tokenInput("/authors.json", {
crossDomain: false,
prePopulate: $("#book_author_tokens").data("pre"),
theme: "facebook"
});
});
$(function() { $("#book_author_tokens").tokenInput("/authors.json", { crossDomain: false, prePopulate: $("#book_author_tokens").data("pre"), theme: "facebook" }); });

