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.
First, you have to add JQuery-UI to your file so it will look like this:
1 2 3 4 | |
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
1 2 3 4 5 6 7 8 9 10 11 12 | |
Next we set up the post model with user_name attribute getter and setter
1 2 3 4 5 6 7 8 9 10 11 12 | |
After this, it’s all CoffeScript which i add to
1 2 | |
And that is everything needed for a nice autocomplete, be sure to include a suitable JQuery-UI theme in your vendor/assets/stylesheets folder.