A Token-input field is one which allows your users to select multiple items from a predefined list, visually highlighting each item as they select it.
There are many apps out there, that use a Token Input field – iOS’s mail app for instance (you know, how it shows names in blue bubbles as you add them in an email).
You can easily add a Token Input field in your Rails app, using just jQuery. Let me show you how to do this, using the jQuery Token-input plugin by James Smith.
To get started, make sure you have jQuery. If not, you can use the jQuery-Rails gem to quickly install it.
[ruby]
gem install jquery-rails
rails g jquery:install
[/ruby]
Next, setup your controller and routes, to process search queries. In this instance we are searching for Book Names (Book being the Rails model, with attribute Name).
[ruby]
#books_controller.rb
def search
@books = Book.where(“name LIKE ?”, “%params[:q]%”)
respond_to do |format|
format.json
end
end
#config/routes.rb
match ‘/search’ => ‘books#search’, :as => :search
[/ruby]
Notice how the params containing the search term is wrapped with %. That will ensure that results include all matches where the search term is contained in any part of the result string.
The output is in JSON format, as required by the plugin.
Setup the View as follows:
[ruby]
<%= form_tag(search_path, :method => ‘get’) do %>
<%= text_field_tag(:q, params[:q]) %>
<% end %>
[/ruby]
Make sure to include this script, either in application.js, or in the layout file. This will load the Token-input plugin on the Text-field with ID ‘q’, the URL parameter being the search URL. Note that while the ID can be anything you want, the query parameter should be ‘q’.
[javascript]
$(document).ready(function () {
$(“#q”).tokenInput(“http://www.yourdomain.com/search.json”);
});
[/javascript]
Finally, add this single line in your model.
[ruby]
self.include_root_in_json = false
[/ruby]
This is required, as the jQuery Token-input plugin should receive only the child nodes i.e ID, Name & other attributes of the book model, in the JSON generated by the controller. If you inspect the default JSON output, it would include the root node also, which is ‘books’.
And with that, you should have auto-complete on your model, in a Text-field. Join me in part-2, where i’ll hopefully take you through using the Token-input field further in your Rails app.