Autocomplete in Rails with Typeahead.js
I decided to use autocomplete in my recent Rails project. I thought this would be easy and there would be a gem for it. Yes, and no. The standard seems to be rails3-jquery-autocomplete. The result is easy to use but an absolute disaster in terms of appearance when used with Bootstrap. The internet seemed to be of little help to finding a solution so I set out on writing my own. I was adding a Vendor, which would be autocompleted, to a new Item.
My first order of business was writing a method for retrieving suggestions, which surprisingly was the easiest part. I had originally simply made the method in Item, but found that strong parameters caused this to be prohibitive as there was no item parameter. Instead, I created a new Suggestions controller.
The fuzzy_search method relies on the Textacular gem which allows for partial searches.
Then, to render it in JSON, the page jbuilder file looks like:
The JSON output and route will look like:
I had to use typeahead.js, instead of the typeahead packaged with Bootstrap, which are two very different things and the one packaged with Bootstrap will be deprecated in version 3.
The collection_select field is unnecessary and was only there for debugging. Essentially, my setup works by registering an onSelected event-listener that is called once an item is chosen, and passes that datum to the function, which sets the value of a hidden vendor_id field that is set as the datum's id field.
Make sure to download and include typeahead.js in your assets.
When finished it looked like: