Ruby on Rails: When script/generate crashes

So I’ve had in mind a project and decided to try it using Ruby on Rails. I already had a copy of this installed, so decided to sudo gem upgrade-all to catch-up, then rails myapp to build the stub application.

Usually after this point you hop in, and run script/generate with arguments to invoke new controllers and models. You know the stuff.

Except I was presented with this:
./script/../config/boot.rb:29: undefined method `gem' for main:Object (NoMethodError)
from script/generate:2

Not particularly helpful. Decided to uninstall the gems for rails including action*, active* and a couple of others too, installing rails afterwards and restoring those other packages as dependencies.

That, alas did not resolve the problem. Nor could the kind souls on irc:// who could only guess that ruby was messed up on the system. Not having a Mac for comparison, they could go no further.

So I checked and found a newer version of the ruby language. Installed it, no help.

So I checked and found a newer version of gem. Indeed ‘sudo gem update –system’ appears to self-update. I reinstalled rails afterwards. Lo and behold, script/generate sprang to life.

Oh happy days. I’m not too tired to proceed. Welcome to my world.

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).