ActiveRecord: Drop/Create database, run migrations, outside of Rails by jgn on Thursday, December 2, 2010 in Code

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):

[code lang='ruby'] 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

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

comments powered by Disqus