Running rails migrations in other databases

Posted Posted by Wes in Ruby on Rails     Comments 4 comments
Sep
24

We have a set of Ruby on Rails applications that shares user logins, so we put that table in a database and connect to it from each application.

If an app needs to add a column to the shared table, you can create a migration that accesses that other database.

First, create an entry in your database.yml file (we name ours “user_development”, etc.).

Then, establish that connection in your database migration and do your migration stuff:

This has the benefit of keeping all the migrations local to the app they’re needed for, but it stores the schema of the users table in the users database where it belongs.

4 Comments to “Running rails migrations in other databases”

  • One potential problem with this is that if this is the first migration against a blank database, it will fail with a “schema_migrations table doesn’t exist” error. This is because the initialize_schema_migrations_table which ensures this exists is being called before the up method is called, so it’s running against the ActiveRecord::Base.connection before you change it.

    To solve this, just add the following line after the establishing the new connection, and all will be fine:

    ActiveRecord::Base.connection.initialize_schema_migrations_table

  • Thank you Ben Hughes. I also have that issue.

  • Thanks for this. It works well. Only one question. How would you reverse the migration?

  • @Hannes:
    You should just be able to do establish_connection and then drop the column/table/index as needed.

Post comment

about databasically

We live and work in Kansas City, USA.

We're passionate about helping small businesses succeed and want to help you use technology to get more done.

From server, desktop, network management to programming custom web applications in Ruby on Rails, we're here to lend a hand.

Contact us if you have any questions!