Skip to content

Instantly share code, notes, and snippets.

@kagemusha
Created December 5, 2011 17:14
Show Gist options
  • Save kagemusha/1434402 to your computer and use it in GitHub Desktop.
Save kagemusha/1434402 to your computer and use it in GitHub Desktop.
JQuery Autocomplete with Rails 3.1 Example
Tested on: Rails 3.1.3, jquery-rails (1.0.18), jquery-ui-1.8.16
Ref: http://jqueryui.com/demos/autocomplete/
Steps:
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
Step 1 Rails Form (in Haml)
= form_for @item do |f|
= f.label :name
= f.text_field :name
= f.submit 'Save'
Step 2 JQuery Autocomplete Code (Coffeescript)
window.itemAutocomplete = ->
url = "/item_ac" #this is rails route
$("#item_name").autocomplete {
source: url,
delay: 500
minLength: 2
}
Notes:
- don't forget to call this function when your page loads
- some jquery docs leave out the source key, but if you forget it you
will get error "source' of object #<Object> is not a function"
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("this.name.match(/#{term}/i)").only(:name) #mongoid
else
matches = {}
end
matchArray = matches.collect {|match| match.name}
render :json=>matchArray.to_json
end
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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment