Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
JQuery Autocomplete with Rails 3.1 Example
Tested on: Rails 3.1.3, jquery-rails (1.0.18), jquery-ui-1.8.16
1. Create form with text field to be autocompleted
2. Hook up autocomplete
3. Write an autocomplete function in your Rails controller to return data
4. Create a rails route
<b>Step 1 Rails Form (in Haml)</b>
= form_for @item do |f|
= f.label :name
= f.text_field :name
= f.submit 'Save'
Step 2 JQuery Autocomplete Code (Coffeescript)
window.initItemForm = ->
url = "/item_ac" #this is rails route
$("#item_name").autocomplete {source: url, {
delay: 500
minChars: 2
- don't forget to call this when ur page loads
- some jquery docs leave out the source key, but if you forget it you
will get error like "source not found"
Step 3 Rails Controller Method
In your Rails controller add method such as this:
#assume finding by :name of :item
def autocomplete
term = params[:term]
if term && !term.empty?
matches = Artist.where("{term}/i)").only(:name)
matches = {}
matchArray = matches.collect {|match|}
render :json=>matchArray.to_json
Step 4 Rails Route
In routes.rb, add a route to your controller function (same as url in step 2)
match "item_ac" => "items#autocomplete"
jquery docs:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment