在rails 3.2中,向遷移添加連接方法不起作用。因此,所有的答案一樣
def connection
@connection ||= ActiveRecord::Base.establish_connection
end
根本行不通的原因是(不能down
,不change
,連接丟失等工作)了的ActiveRecord ::遷移和遷移類具有硬編碼到ActiveRecord的連接:: Base allovertheplace。
幸運的是this post指向我this ticket這有一個很好的解決方案,即覆蓋實際的rake task。
最後我用一個稍微不同的rake任務,這樣我就可以具體談談我在不同的數據庫上運行遷移(我們試圖支持多個數據庫版本):
這裏是我的lib /任務/數據庫.rake
# Augment the main migration to migrate your engine, too.
task 'db:migrate', 'nine_four:db:migrate'
namespace :nine_four do
namespace :db do
desc 'Migrates the 9.4 database'
task :migrate => :environment do
with_engine_connection do
ActiveRecord::Migrator.migrate("#{File.dirname(__FILE__)}/../../nine_four/migrate", ENV['VERSION'].try(:to_i))
end
end
end
end
# Hack to temporarily connect AR::Base to your engine.
def with_engine_connection
original = ActiveRecord::Base.remove_connection
ActiveRecord::Base.establish_connection("#{ Rails.env }_nine_four")
yield
ensure
ActiveRecord::Base.establish_connection(original)
end
這使我們能夠把具體到一個數據庫遷移在自己的子目錄(nine_four /遷移,而不是DB /遷移)。 它還爲每個數據庫在其模式和遷移版本方面提供完全隔離。唯一的缺點是有兩個rake任務要運行(db:migrate和nine_four:db:migrate)。
謝謝,稍作更正:我更改了require'activerecord'以要求'active_record' – valk 2015-04-19 11:55:07