Tuesday, May 23

Automatic foreign keys in your migrations

A couple weeks back, Simon Harris blogged about a little plug-in he'd whipped up which makes your Ruby on Rails database migrations automatically guess and apply foreign key relationships. This was something I had been yearning for, so I jumped all over it. Unfortunately, it had a few problems:

- It didn't work with the Windows port of Ruby 1.8.4. Simon had developed and tested it on the OSX port of Ruby 1.8.4 and method aliasing -- for some reason -- isn't consistent between the two.

- It didn't work with MySQL. Simon had developed and tested it for PostgreSQL and the SQL syntax support differed slightly.

- It didn't handle column names that weren't clearly evident, so adhering to the Ruby on Rails philosophy, I recommended a little "configuration" to spice up the "convention".

- It choked on columns that looked like foreign keys but were not, attempting to create foreign keys to nonexistent tables.

- It didn't consistently properly pluralize table names.

Believe it or not, the set of migrations for my current pet project is complex enough to have exposed all of these issues.

So my correspondence with Simon graduated from comments on his blog to direct e-mails, and by last night we were lobbing chunks of code back and forth by the minute. We probably should have switched to some form of instant messaging, but we had our heads buried deep in the code. Due to the time difference (Simon is in Oslo at the moment, and I'm in South Florida) he was up until 1:30 in the morning (his time) working out the final kinks.

And by the grace of the Heavens, we finally got it perfect. My complex migrations run from beginning to end, perfectly applying every foreign key. This is my new favorite plug-in, and I'm proud to have helped it to fruition.

Simon has posted the latest and greatest version on RubyForge. Check it out!

1 comment:

girish said...

Solution is as simple as modifying your environment.rb file as posted in http://railsforum.com/viewtopic.php?pid=31916