ActiveRecord: Drop/Create database, run migrations, outside of Rails

by john on December 2, 2010

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

  • http://movie-cat.tv Rajat

    Dear John,
    I was a student of yours a while back in E168, Ruby on Rails.

    When you taught the class, you suggested we start with a basic ruby on rails install, write models and several initial migrations, create controllers and views, and start rolling.

    My question is this: Has anything changed since then? Are there any new approaches that you’d suggest to get a new project starting, or is it the same old process?

    At the startup where I work, OPOWER, we have an innovation day next week where we get to write something creative that will help the company, not necessarily in a pure business sense. My project will be an RoR project. I am going to create a webapp to model where our clients are and what products they’re using. It will hopefully feed into a google maps api for visualization.

    Any tips are appreciated! I know how quickly the RoR environment changes. Cheers,
    Raj

  • http://7fff.com john

    Raj – Everything is pretty much the same. There are a fair number of changes in Rails 3.x, but I don’t think there’s anything wrong with using an older version of Rails if you’re comfortable with it.

  • http://www.deploymentzone.com Charles Feduke

    Very useful post, allowed me to get rolling with TDDing a gem without requiring a full Rails 3.x stack as part of my spec. Thanks!

  • Deepak Kumar

    Very useful, simple and clear instructions. Saved a lot of time for me.

  • http://pikachuexe.weebly.com/ Leung Ho Kuen

    Thanks!
    I got a bug that is PostgreSQL only in a gem, just wondering how to run test in it

Previous post:

Next post: