Simple auto-complete in Ruby on Rails

The Slash7 tutorial on Ajaxariffic Autocomplete with Scriptaculous was helpful, but it is a bit outdated, considering that it is from 2005.

You’re going to want to download the latest version of Scriptaculous directly from its website – the article links to the current version at the time of writing, in 2005.

The Ruby pieces that it suggests using (text_field_with_auto_complete and auto_complete_for) were moved to the auto_complete plugin in Rails 2.0. You can install this using the command “ruby script/plugin install [URL on github page]“.

Per the plugin’s wiki, you need to use text_field_with_auto_complete‘s fourth parameter, :method => :get, or you will continually have authentication token errors like I did and potentially be redirected to your app’s login page!

Editing the CSS isn’t as easy as she suggests – it’s now put directly into the page (bad design!). I took the CSS out of vendor/plugins/auto_complete/lib/auto_complete_macros_helper.rb (it’s near the bottom of the file in my version) and put it into my normal stylesheet, so that I could edit it more easily.

I didn’t like how the default CSS has the auto-complete box appearing over top of the text field, so I added the following two lines to div.auto_complete:

  • margin-top: 15px;
  • margin-left: 8px;

And now, I have a very simple auto-complete that populates my text field from data in the database that is already in the text field! The next steps are to figure out a) more complex auto-completion with a hidden ID field and b) how to do something based on the auto-complete result, i.e. populate other fields.

This entry was posted in Ruby on Rails and tagged . Bookmark the permalink. Both comments and trackbacks are currently closed.

2 Comments

  1. Posted October 19, 2011 at 8:44 am | Permalink

    this works for rails 3.1???

  2. Tara
    Posted October 19, 2011 at 7:17 pm | Permalink

    Hi Roman, I’m actually working with Rails 2.3.11, not Rails 3.1. I would love to know if this still works for Rails 3.1!