Faster Auto-Completion with Rails

Posted in HowTo, Ruby on Rails

Derek
Derek
15
Jun

Auto-Complete is a great tool when it provides possible results BEFORE you finish typing. Unfortunately, using Rails’s included AJAX helpers to query the database as you type often results in a large delay before matches are returned.

However, there is a lightning-quick option: pre-fetch the results in a Javascript array.

In a client project, users can add labels to events on their calendar. To prevent users from creating variations of the same label name (i.e. – “favorite” vs. “favorites”), we needed to provide faster auto-complete functionality than that available through Rails’s provided AJAX helpers.

We created a simple helper method for this case (special thanks to Chad Fowler and his Rails Recipes book for the inspiration).

Take a look at the local_auto_complete_field helper method. TXT

To call the function from your views:
<%= local_auto_complete_field('name',@labels) %>

In the above example, we are adding JavaScript-powered auto-complete functionality to the 'name' text field. The JavaScript array is generated by calling #name on each element in the @labels array. To override this behavior:

<%= local_auto_complete_field('name',@labels, 
                              :method => 'description') %>

Here’s to faster auto-completion!

Comments

  1. Sam said 4 days later:
    Little bit more info if poss... What do you call the file with the modules in and where do you place it (./lib ?) and does it need requiring..?
  2. Derek said 5 days later:

    Sam,

    • Put the file in your /lib directory.
    • I’d call it “local_autocomplete.rb”...but the name shouldn’t matter.
    • You don’t need to require it…Rails loads files in the /lib folder automatically.

Comments are disabled