Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Rails Migration on different database than standard "production" or "development"

I have a rails project running that defines the standard production:, :development and :test DB-connections in config/database.yml

In addition I have a quiz_development: and quiz_production: definition pointing to a differnet host/db/user/password

My goal now is to define a Migration that uses "quiz_#{RAILS_ENV}`" as its database configuration.

What I have tried (and failed):

  • Setting ActiveRecord::Base.connection in the Migration file
  • Changing the db:migrate task in rails to set ActiveRecord::Base.connection there

Question:

How can I make rake db:migrate use that other database definition?

Thanks, Frank

like image 751
thenoseman Avatar asked Sep 10 '09 11:09

thenoseman


People also ask

Is it possible to use two databases in a single application in Ruby on Rails?

Rails now has support for multiple databases so you don't have to store your data all in one place. At this time the following features are supported: Multiple writer databases and a replica for each. Automatic connection switching for the model you're working with.

How do I run a specific Rails migration?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users. rb , you would use 20160515085959 as the version number.

What can Rails migration do?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.

Why do we need migration in Rails?

Migrations are a convenient way to alter your database schema over time in a consistent way. They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent. You can think of each migration as being a new 'version' of the database.


1 Answers

There's a much easier answer. Add this to your migration:

def connection   ActiveRecord::Base.establish_connection("quiz_#{Rails.env}").connection end 

That's for Rails 3.1. For Rails 2.X or 3.0 it's a class function instead (eg def self.connection)

like image 59
Bryan Larsen Avatar answered Oct 15 '22 00:10

Bryan Larsen