[Ruby] AR migration problems? was: refactoring/drying help

Jack Danger Canty seattle.rb at 6brand.com
Fri Oct 12 13:05:08 PDT 2007


>
>  If on migration 39 you had a model MyThingy and by
> 189 it is now called something Thingy, you only need to go back to 39
> and add:
>
>         class MyThingy < ActiveRecord::Base; end
>
> at the top of the file.


If the model hasn't changed much then it's not to tough to make that change.
 But what about some really complicated stuff?  For example, I once had a
migration that looked something like this

def self.up
  orphaned_listings = Account.find(:all, :conditions => 'logged_in_at is not
null').sites.map {|site| site.listings.find(:all, :conditions => 'owner_id
is null') }
end

About 50 migrations later I'd changed the conditions for logged_in_at, the
sites association had been renamed and listings was now one level removed
from sites (there was an additional join model).  Urgh.

So I turned it into SQL and now it's bulletproof.

Start by making a rake task called 'nuke' that wipes the db and
> migrates. Run it. Make changes like the above until you've got a full
> run done. This makes it much much easier for someone new to come in
> and work on your stuff.


I've got a bash alias 'remigrate' tied to 'rake db:migrate VERSION=0 && rake
db:migrate'
It helps to be able to test that the down migrations are working just as
well as the up.

> > Bonus feature: the migrations are much smaller and a little faster.
> > and a little harder to maintain.


That's the beauty of it: you don't ever have to maintain SQL in a migration
no matter what happens to the models (or if the whole app disappears).


More information about the Ruby mailing list