Sometimes it can be convenient to drop and create databases, and run migrations, outside of Rails — or rake. Here’s one way to do it in code (Ruby 1.9.2):
require 'active_record'
require 'pg'
PG_SPEC = {
:adapter => 'postgresql',
:host => 'localhost',
:database => '7fff',
:username => 'postgres',
:encoding => 'utf8'
}
# drops and create need to be performed with a connection to the 'postgres' (system) database
ActiveRecord::Base.establish_connection(PG_SPEC.merge('database' => 'postgres', 'schema_search_path' => 'public'))
# drop the old database (if it exists)
ActiveRecord::Base.connection.drop_database PG_SPEC[:database] rescue nil
# create new
ActiveRecord::Base.connection.create_database(PG_SPEC[:database])
ActiveRecord::Base.establish_connection(PG_SPEC)
class CreateBlog < ActiveRecord::Migration
def self.up
create_table :blog do |t|
t.string :title
t.timestamps
end
end
def self.down
drop_table :blog
end
end
CreateBlog.up
Note that the code here is PostgreSQL-specific. To see how to do it properly for MySQL or Sqlite3, take a look at your ActiveRecord gem, at lib/active_record/railties/databases.rake
