起きたこと
複数databaseのmigrationを参考にさせていただいて、使っているのだが、db:migrateができない。
環境
Gemfile
gem 'rails', '4.1.7'
# デフォルトじゃない方のDBはsqlite3
gem 'sqlite3'
エラー内容
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: no such table: synset: ALTER TABLE "synset" ADD "is_addition" boolean DEFAULT 'f' NOT NULL/Users/ryohei/talker/vendor/bundle/gems/sqlite3-1.3.10/lib/sqlite3/database.rb:91:in `initialize'
そんなテーブルはないと言われる。。。
原因
案の定、デフォルトの方のテーブルを見に行っていた。
解決方法
ActiveRecord::Migrationがこんな感じになっているので、
active_record/lib/migration.rb
def connection
@connection || ActiveRecord::Base.connection
end
設定時にオーバーライドする
other_db.rake
task :set_custom_db_config_paths do
ENV['SCHEMA'] = 'other_db/schema.rb'
Rails.application.config.paths['db'] = ['other_db']
Rails.application.config.paths['db/migrate'] = ['other_db/migrate']
Rails.application.config.paths['db/seeds.rb'] = ['other_db/seeds.rb']
Rails.application.config.paths['config/database'] = ['config/other_db.yml']
ActiveRecord::Migrator.migrations_paths = 'other_db/migrate'
ENV['db_model'] = "OtherDb"
# 以下を追記
class OtherDbMigration < ActiveRecord::Migration
def connection
@connection = OtherDb.connection
end
end
end
migrationファイルも以下のように変更
other_db.rake
class AddIsAdditionToSynset < OtherDbMigration #OtherDbMigrationを継承するようにする
def change
add_column :synset, :is_addition, :boolean, null:false, default:false
end
end
多分もっといい方法があると思いますが、とりあえず。。。!