我创建了一个连接到 2 个数据库的类:
class Production < ActiveRecord::Base
ActiveRecord::Base.establish_connection(:production)
self.abstract_class = true
attr_accessor
end
class Backup < ActiveRecord::Base
ActiveRecord::Base.establish_connection(:backup)
self.abstract_class = true
attr_accessor
end
class RepairReport
def init
end
def repair_now
Production.table_name = "users"
users = Production.all
users.each do |user|
puts "USER: #{user.last_name}"
end
end
end
这是database.yml
:
production:
adapter: postgresql
encoding: unicode
database: test_eagle_development
host: localhost
pool: 296
username: postgres
password: password1
template: template0
backup:
adapter: postgresql
encoding: unicode
database: test_eagle_test
host: localhost
pool: 5
username: postgres
password: password1
template: template0
当我运行它时,它给出了一个错误: ActiveRecord::AdapterNotSpecified: 'production' database is not configured. Available: ["development", "test"]
当我更改database.yml
为development
并且test
它可以工作时,但输出的用户来自另一个本地 Rails 应用程序中使用的另一个数据库。所以看起来旧的连接仍然有效?如何确保连接了正确的数据库?
更新:
现在这是我的更新database.yml
和代码(见下文),但它仍然连接到错误的数据库。当我删除development
和test
部分时,它返回:ActiveRecord::AdapterNotSpecified: 'development' database is not configured. Available: ["development_prod", "development_backup"]
,所以它似乎正在读取正确的database.yml
.
development:
adapter: postgresql
encoding: unicode
database: test_eagle_development
host: localhost
pool: 296
username: postgres
password: password1
template: template0
test:
adapter: postgresql
encoding: unicode
database: test_eagle_test
host: localhost
pool: 5
username: postgres
password: password1
template: template0
development_prod:
adapter: postgresql
encoding: unicode
database: test_eagle_development
host: localhost
pool: 296
username: postgres
password: password1
template: template0
development_backup:
adapter: postgresql
encoding: unicode
database: test_eagle_test
host: localhost
pool: 5
username: postgres
password: password1
template: template0
和代码:
class Production < ActiveRecord::Base
ActiveRecord::Base.establish_connection("#{Rails.env}_prod".to_sym)
self.abstract_class = true
attr_accessor
end
class Backup < ActiveRecord::Base
ActiveRecord::Base.establish_connection("#{Rails.env}_backup".to_sym)
self.abstract_class = true
attr_accessor
end
似乎您正在development
模式下运行 rails 应用程序。默认情况下,rails 尝试加载数据库配置并按RAILS_ENV
值获取连接详细信息。
我建议将连接命名为两个匹配环境:
development:
adapter: postgresql
encoding: unicode
database: test_eagle_development
host: localhost
pool: 296
username: postgres
password: password1
template: template0
development_backup:
adapter: postgresql
encoding: unicode
database: test_eagle_test
host: localhost
pool: 5
username: postgres
password: password1
template: template0
class Production < ActiveRecord::Base
ActiveRecord::Base.establish_connection(Rails.env)
self.abstract_class = true
end
class Backup < ActiveRecord::Base
ActiveRecord::Base.establish_connection("#{Rails.env}_backup")
self.abstract_class = true
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句