24
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

複数databaseのmigration

Posted at

複数のdatabaseもきちんとmigrationを使って管理したいです。

たとえば foo というデータベースを追加で管理したい場合、以下のようなrakeタスクを作ることで良い感じに運用できます。

lib/tasks/database_foo.rake
namespace :foo do

  desc "Configure the variables that rails need in order to look up for the db
    configuration in a different folder"
  task :set_custom_db_config_paths do
    ENV['SCHEMA']                                     = 'db_foo/schema.rb'
    Rails.application.config.paths['db']              = ['db_foo']
    Rails.application.config.paths['db/migrate']      = ['db_foo/migrate']
    Rails.application.config.paths['db/seeds.rb']     = ['db_foo/seeds.rb']
    Rails.application.config.paths['config/database'] = ['config/database_foo.yml']
    ActiveRecord::Migrator.migrations_paths           = 'db_foo/migrate'
  end

  namespace :db do
    task drop: :set_custom_db_config_paths do
      Rake::Task["db:drop"].invoke
    end

    task create: :set_custom_db_config_paths do
      Rake::Task["db:create"].invoke
    end

    task migrate: :set_custom_db_config_paths do
      Rake::Task["db:migrate"].invoke
    end

    task rollback: :set_custom_db_config_paths do
      Rake::Task["db:rollback"].invoke
    end

    task reset: :set_custom_db_config_paths do
      Rake::Task['db:drop'].invoke
      Rake::Task['db:create'].invoke
      Rake::Task['db:migrate'].invoke
    end

    task seed: :set_custom_db_config_paths do
      Rake::Task["db:seed"].invoke
    end

    task version: :set_custom_db_config_paths do
      Rake::Task["db:version"].invoke
    end

    namespace :test do
      task prepare: :set_custom_db_config_paths do
        Rake::Task['db:drop'].invoke
        Rake::Task['db:create'].invoke
        Rake::Task['db:migrate'].invoke
      end
    end
  end

end

railsのルートに

  • db_foo
  • db_foo/migrate/.keep
  • db_foo/schema.rb
  • db_foo/seeds.rb

を配置します。
もともと db ディレクトリにあるファイル群と同じです。

それと config/database_foo.yml を配置します。これももともとある database.yml と同様のものです。

これでdb周りのタスクが別databaseに対して使えるようになります。

migrateしたい場合には

$ rake foo:db:migrate

となります。

24
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?