Using Migrations in ActiveRecord without Rails

As I slowly progress toward working with Rails, I wanted to figure out how to implement migrations without Rails.  Taking the code from the previous posts, I’ve modified the code to use a migration to create the “user” table, do my tests, then drop the user table.

My test “main” now looks like this:

require 'active_record'
require 'logger'
require 'yaml'

# Note that the class doesn't define any properties
class User < ActiveRecord::Base
end

class ActiveRecordTest
  # Create a connection.
  def connect
    #use YAML to define the connection information.
    dbconfig = YAML::load(File.open('database.yml'))
    ActiveRecord::Base.establish_connection(dbconfig)
    #Enable logging
    ActiveRecord::Base.logger = Logger.new(STDERR)
  end

  # Add a user.
  def addUser(id, username)
    user = User.new
    user.id = id
    user.name = username
    user.save
  end

  # Query the user table, allowing the caller to handle the returned User records.
  def queryUserTable
    User.all.each {|user| yield user}
  end

end

def main
  ar = ActiveRecordTest.new
  ar.connect
  # sync the database with migration 001
  ActiveRecord::Migrator.migrate("./Migrations", 1)
  begin
    ar.addUser(1, "Marc")
    ar.addUser(2, "Sharon")
    ar.queryUserTable {|user| printf("%d %s\n", user.id, user.name)}
  rescue Exception => e
    puts e.message
    puts e.backtrace.inspect
  ensure
    #revert the database to version 000
    ActiveRecord::Migrator.migrate("./Migrations", 0)
  end
end

main

and the migration class, 001_create_user_table.rb, looks like this:

require 'active_record'

class CreateUserTable &lt ActiveRecord::Migration
  def up
    create_table :users do |t|
      t.integer :id
      t.string :name
      # or
      # t.column :id, :integer
      # t.column :name, :string
    end
  end

  def down
    drop_table :users
  end
end

If you’re curious, I’m indebted to these folks:

for the invaluable and succinct descriptions of how to do this. Quite frankly, the only reason I’m blogging about it here is because I wanted to test this myself using my own examples, which I find is a really good way to learn new technologies.

Advertisements

One thought on “Using Migrations in ActiveRecord without Rails

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s