Skip to content

Instantly share code, notes, and snippets.

@kagemusha
Created December 5, 2011 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment