LoginSignup
13

More than 5 years have passed since last update.

Railsでデータベースを分けてmigrationを実行する方法(+modelとdatabase.yamlの書き方)

Last updated at Posted at 2014-03-24

概要

  • 今回の要件は、master slaveを作るのでなく、テーブルを分けたい
  • 専用のrakeタスクを作成した
  • railsのissueでやり取りがあったけど、古いしバグもありいろいろ直すのが大変だった。。

rake

  • lib/tasks以下に配置
  • your_engineには好きな名前で置き換える
  • rake your_engine:db:migrateで実行
  • (establish_connectionをmigrationの中で実行すると、migrationのversion管理がうまく動かなくなる。)
database.rake
engine = "your_engine_name"

# Run custom task before original task
task 'db:migrate' => "#{engine}:db:migrate"
task 'db:schema:dump' => "#{engine}:db:schema:dump"
task 'db:schema:load' => "#{engine}:db:schema:load"

engine_namespace = namespace engine.to_sym do
  namespace :db do
    @engine = engine
    desc "Migrates the #{engine} database"
    task :migrate => :environment do
      p "#{engine} db migrate"
      with_engine_connection do
        ActiveRecord::Migrator.migrate("#{File.dirname(__FILE__)}/../../db/#{@engine}_migrate", ENV['VERSION'].try(:to_i))
      end
    end

    desc "Dump #{engine} schema"
    task :'schema:dump' => :environment do
      require 'active_record/schema_dumper'

      with_engine_connection do
        File.open(File.expand_path("../../../db/#{@engine}_schema.rb", __FILE__), 'w') do |file|
          ActiveRecord::SchemaDumper.dump ActiveRecord::Base.connection, file
        end
      end
      engine_namespace['db:schema:dump'].reenable
    end

    desc "Load #{engine} schema"
    task :'schema:load' => :environment do
      with_engine_connection do
        load File.expand_path("../../../db/#{@engine}_schema.rb", __FILE__)
      end
    end

    # Hack to temporarily connect AR::Base to custom database engine.
    def with_engine_connection
      original = ActiveRecord::Base.remove_connection
      ActiveRecord::Base.establish_connection "#{@engine}_#{Rails.env}".to_sym
      yield
    ensure
      ActiveRecord::Base.establish_connection original
    end
  end
end

ついでにモデルとdatabase.ymlの設定

Model

class YourModel < ActiveRecord::Base
    establish_connection "your_engine_#{Rails.env}".to_sym
end

database.yml

your_engine_development:
  adapter: 
  database:
  encoding:
  username:
  password:
  host:

参考

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
13