public
Created

JQuery Autocomplete with Rails 3.1 Example

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
Tested on: Rails 3.1.3, jquery-rails (1.0.18), jquery-ui-1.8.16
 
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
 
<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
}
 
Notes:
- 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("this.name.match(/#{term}/i)").only(:name)
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"
 
 
Ref:
jquery docs: http://docs.jquery.com/Plugins/Autocomplete

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.