I’m in the process of building a Rails application and needed to introduce some autocomplete functionality on a couple of text fields.

If you’re using Rails 3 and are not working with jQuery and the jQuery UI library, then there is a solid gem you may want to checkout; otherwise, here’s how you can setup autocomplete on a text field using Rails 3, jQuery, and jQuery UI.

First, make sure to properly include the jQuery UI stylesheets and JavaScript sources in the related layouts:

<%= stylesheet_link_tag "reset", "layout", "themes/base/jquery.ui.all" %>
<%= javascript_include_tag "jquery.ui.core", "jquery.ui.widget", "jquery.ui.position", "jquery.ui.autocomplete" %>

Next, locate the controller action that will load the collection used to populate the autocomplete field. For me, I was using both new and edit.

Specifically, I wanted to load all of the locations associated with each contact in the system.

Since locations aren’t required fields in the rest of the application, I also needed to remove the empty entries from the collection hence the need for compact and reject.

def new
	# Irrelevant code snipped
	@locations = Contact.all.map(&:location).compact.reject(&:blank?)
end

Because this particular action will be called for both synchronous and asynchronous requests, I needed to introduce two handles for the response.

Specifically, the action will serve the HTML view whenever the browser accesses the page and will return the JS view when for ajax requests:

def new
	# Irrelevant code snipped
	@locations = Contact.all.map(&:location).compact.reject(&:blank?)
	respond_to do |format|
		format.html
		format.js
	end
end

After that, I added a view – new.js.erb – to respond to the ajax request. It’s purpose is to simply return the raw collection:

<%= raw @locations %>

Finally, I hooked up the text field to the newly created view by adding the following code to application.js. Simply put, this displays an autocomplete list for the text field having the ID of contact_location:

$(function() {

	$('#contact_location').autocomplete({
		source: '/contacts/new.js'
	});

});

Again, I recommend this route only if you’re already using jQuery and it’s UI library within the context of your project; otherwise, sticking with a gem may be a better option.