我正在尝试使用establish_connection
迁移到Rails中的单独数据库。我在迁移文件中有类似的内容:
def change
ActiveRecord::Base.establish_connection("user_#{Rails.env}")
ActiveRecord::Base.initialize_schema_migrations_table
create_table "users", :force => true do |t|
t.string "email",
end
在yml中我有这个配置:
user_development:
adapter: postgresql
encoding: unicode
database: MyApp_user_development
pool: 5
host: localhost
username: xxx
password: xxx
我也定义了这样的用户模型:
class User < ActiveRecord::Base
establish_connection "user_#{Rails.env}"
[...]
end
现在,数据库已存在,但在运行rake db:migrate
时出现此错误:
== CreateUserOnSeparateDb: migrating =========================================
rake aborted!
An error has occurred, this and all later migrations canceled:
connection is closed
你们有谁知道发生了什么事?
我还尝试将establish_connection
调用移动到迁移文件中的connection
方法。在这种情况下,表是在迁移时创建的,但后来我得到了相同的错误(因此以某种方式在其他迁移中失败),并且它没有创建schema_migrations表...
任何帮助?
答案 0 :(得分:1)
按照以下步骤解决了上述问题。
class AddCustomTbl < ActiveRecord::Migration
def connection ActiveRecord::Base.establish_connection(Rails.env).connection end def up # Connection with user_#{Rails.env} oldEnv = Rails.env Rails.env = "user_#{Rails.env}" ActiveRecord::Base.establish_connection(Rails.env) create_table "users", :force => true do |t| t.string "email" end # Connection with Rails.env Rails.env = oldEnv ActiveRecord::Base.establish_connection ActiveRecord::Base.configurations[Rails.env] end def down # Connection with user_#{Rails.env} oldEnv = Rails.env Rails.env = "user_#{Rails.env}" ActiveRecord::Base.establish_connection(Rails.env).connection drop_table :users # Connection with Rails.env Rails.env = oldEnv ActiveRecord::Base.establish_connection ActiveRecord::Base.configurations[Rails.env] end end