Fun with text_field_with_auto_complete

I’ve spent the past few hours trying to get my head around Railstext_field_with_auto_complete. Rails, from a PHP background is totally different paradigm and text_field_with_auto_complete illustrates this more so than usual.

So I have a web site home page /home which has a controller named ‘HomeController’ amazingly enough. I also have a complete MVC ‘WebSite’ for listing of web sites. I wanted a search field on the home page to type in a url and have it autocomplete.

Now it turns out that the solution was incredibly simple, and I used this autocomplete blog entry by Cloves Carneiro Jr as my starting point. But I just had to complicate things unnecessarily. I assumed that the autocomplete box should query the ‘WebSitesController’ as that’s what handles the MCV work for that class. Natural, except I was wrong.

The key was that when the autocomplete makes an AJAX request it HTTP GETs /home/auto_complete_for_model_field or in my specific case, /home/auto_complete_for_web_site_url. At the top of HomeController all I needed was the following line:

auto_complete_for :web_site, :url

I needed no method definition, no view, and no helper. Nothing, zip, nada. Reloaded the page, hit the ‘h’ key and all listed websites appeared. Of course, the next job is to optimise!

Note: Debugging this was made massively easy thanks to FireBug (1.0 beta rocks).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: