Safely plug a Rails app into an existing database

rails deploymentTraditionally there’re a few ways to set up your Rails database using rake tasks:
rake db:create db:migrate
Create a new database and run migrations
rake db:schema:load
Drop database if it exists and create tables according to your schema.
rake db:setup
Will run both rake db:schema:load and rake db:seed

db:schema:load is problematic. It is suggested in Rails schema.rb file that this is an efficient way (compared to db:migrate) to set up your database. However, it assumes that a) you have a database dedicated to the Rails app, b) have no existing data. But what if you want to create tables for your Rails app in an existing database with other important data?

Here’s a guide I’ve come up with on how to forgo migrations and integrate your Rails app into an existing database:

 1. Create tables in your production database
Feel free to namespace them like this: myproject_users instead of just users.

2. Edit database.yml
Specify the name of your database and the user/password that has access to it under the corresponding environment setting (development or production).

3. Void migration files
Under db/migrate, either comment out the files’ content or change their extension to .txt.

4. Schema dump
db/schema.rb is auto generated by running migrations. Since you don’t plan to run them, rake db:schema:dump will update schema.rb and allow it to be used with ActiveRecord.

5. Set custom table names for models
If the name of the tables are different from ActiveRecord convention (e.g.: you namespace the tables), add this to the model self.table_name = "[custom table name]". This will help Rails find the tables and avoid error.

Hope that was somewhat helpful. I’m also looking into deploying with Capistrano and submitting a pull request that would give a warning when you try to run rake db:schema:load.

Advertisements