First, make sure your rails app is setup with jQuery support.
Here’s the general process I use to setup autocomplete for Rails 3:
- Create a method to handle the autocomplete search request
- Add a route for the method you created in the controller – this is your autocomplete search endpoint
- Add a text field with a unique class name like ‘autocomplete’
- Add a unique data attribute like ‘data-endpoint’ to the text field and set it to the path of your autocomplete endpoint
- Enable jQuery Autocomplete on any DOM element with the class ‘autocomplete’ (or whatever you used in the view)
- Use the value of data-endpoint as the source URL for the jQuery Autocomplete widget
In the following example, I’m tagging a user and using autocomplete to help suggest tags.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
The tags controller has two methods. One for creating a tag, and one (index) for handling tag autocomplete searches.
The index method expects user_id and term params. In this example, the user_id is being handled in the path /users/:user_id/tags and jQuery Autocomplete sends in the term param.
1 2 3
This creates a /users/:user_id/tags route and a users_tags_path helper to use in your views.
1 2 3 4 5
1 2 3 4 5 6
That’s all there is to it. You can easily modify your controller and model code to use MongoDB, Solr, Redis, or whatever you want.