Almost every time you create a web application you will have to add at least one autocomplete field in your application. Here is one of the possible ways of doing it. I will be using Rails 3.1.beta1, JQuery-UI and CoffeScript to make it happen.
I have two models in my app, post(title, body) and user(name, email) and i want to select user with autocomplete when creating the post. As a prerequisite, i have created 100 users with Faker gem.
Next, we set up an ajax controller with rails g controller ajax users to have a controller with users action and automatic route. I like to call the controller ajax, or autocomplete, to keep things organized for this. Here is the ajax controller with everything just rendered into json that suits JQuery-UI autocomplete format
Next we set up the post model with user_name attribute getter and setter
After this, it’s all CoffeScript which i add to
And that is everything needed for a nice autocomplete, be sure to include a suitable JQuery-UI theme in your vendor/assets/stylesheets folder.