2008-10-07 70 views

回答

37

你也可以做到這一點很容易沒有硬編碼任何東西,自動運行遷移:

customer = CustomerModel.find(id) 
spec = CustomerModel.configurations[RAILS_ENV] 
new_spec = spec.clone 
new_spec["database"] = customer.database_name 
ActiveRecord::Base.establish_connection(new_spec) 
ActiveRecord::Migrator.migrate("db/migrate_data/", nil) 

我發現它有用以後重新建立一個特定的模式舊的連接:

CustomerModel.establish_connection(RAILS_ENV) 
+0

爲什麼需要文件系統上的路徑? – 2017-05-16 20:22:10

14

您可以通過調用的ActiveRecord :: Base.establish_connection(...)

IE隨時更改連接到的ActiveRecord:

ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev", 
    :username => "root", :password => "password" }) 
+1

請注意,這將清除您的緩存 - 因此它會爲每個表執行「顯示類似%eachtable%的表」並顯示「create table」。如果您在每個請求上創建新連接,則只有一個問題... – Kevin 2013-06-18 23:59:22

6

這已經有一段時間,因爲這個問題已經被創建,但我不得不說,有太多另一種方式:

conn_config = ActiveRecord::Base.connection_config 
conn_config[:database] = new_database 
ActiveRecord::Base.establish_connection conn_config 
1
class Database 
    def self.development! 
    ActiveRecord::Base.establish_connection(:development) 
    end 

    def self.production! 
    ActiveRecord::Base.establish_connection(ENV['PRODUCTION_DATABASE']) 
    end 

    def self.staging! 
    ActiveRecord::Base.establish_connection(ENV['STAGING_DATABASE']) 
    end 
end 

而且在.env(與dotenv-rails創業板爲例):

PRODUCTION_DATABASE=postgres://... 
STAGING_DATABASE=postgres://... 

,現在你可以:

Database.development! 
User.count 
Database.production! 
User.count 
Database.staging! 
User.count 
# etc. 
相關問題