Search

Faster Auto-Completion with Rails

Derek

1 min read

Jun 14, 2006

Faster Auto-Completion with Rails

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 (Editor’s note: this is no longer available.)

To call the function from your views:

<br></br> <%= local_auto_complete_field('name',@labels) %><br></br>

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!

Josh Justice

Reviewer Big Nerd Ranch

Josh Justice has worked as a developer since 2004 across backend, frontend, and native mobile platforms. Josh values creating maintainable systems via testing, refactoring, and evolutionary design, and mentoring others to do the same. He currently serves as the Web Platform Lead at Big Nerd Ranch.

Speak with a nerd

Schedule a call today! Our team of nerds are ready to help

Let's Talk

Related Posts

We are ready to discuss your needs.

Stay in Touch WITH Big Nerd Ranch News