DataMapper Migrations

Oct 05, 2008

I've been working on some merb related things of late, and I'm planning on writing a more detailed article on creating a merb application from scratch as so many of the tutorials out there kind of leave you hanging. In the interim though, I'm just going to touch on a little nugget of information that isn't very well publicised regarding DataMapper, one of the ORMs that gets used with merb.

ActiveRecord Style Migrations with DataMapper

That's right, you aren't left having to wrestle with the command line and ALTER TABLE statements just because you've left ActiveRecord behind. All the migration joy you've come to love with ruby on rails can come and live with you happily with merb and DataMapper.

First things first, you'll want to generate a new migration:

merb-gen migration my_migration

We should now have a file named 001_my_migration.rb and if we look at it, it won't be too foreign based on our ActiveRecord experiences:

migration 2, :my_migration do
  up do
  end

  down do
  end
end

To pad it out with some code that is actually useful, add in the definitions for what you want done:

migration 2, :my_migration do
  up do
    create_table(:posts) do
      column(:id, Integer, :serial => true)
      column(:title, String, :size => 255)
      column(:description, Text)
      column(:published, Boolean)
      column(:created_at, DateTime)
      column(:updated_at, DateTime)
    end
  end

  down do
    drop_table(:posts)
  end
end

Running the DataMapper Migration

And now that we've got the migration we are happy with, applying it to our underlying database is just a matter of the following:

rake dm:db:migrate
Hi, I'm Glenn! 👋 I've spent most of my career working with or at startups. I'm currently the Director of Product @ Ockam where I'm helping developers build applications and systems that are secure-by-design. It's time we started securely connecting apps, not networks.

Previously I led the Terraform product team @ HashiCorp, where we launched Terraform Cloud and set the stage for a successful IPO. Prior to that I was part of the Startup Team @ AWS, and earlier still an early employee @ Heroku. I've also invested in a couple of dozen early stage startups.