在Rails应用中配置多数据库可以通过以下步骤实现:
default: &default
adapter: postgresql
encoding: unicode
pool: 5
username: postgres
password: password
host: localhost
development:
<<: *default
database: myapp_development
test:
<<: *default
database: myapp_test
production:
<<: *default
database: myapp_production
other_database:
<<: *default
database: other_database
config.active_record.database_selector = { delay: 2.seconds }
config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
config.active_record.railtie_name = "myapp"
config.databases = YAML.load_file(Rails.root.join('config', 'database.yml'))
config.databases.each do |name, db_config|
config.database_configuration = db_config.with_indifferent_access
ActiveRecord::Base.configurations[name.to_s] = config.database_configuration
end
class User < ActiveRecord::Base
establish_connection :development
end
class OtherModel < ActiveRecord::Base
establish_connection :other_database
end
通过以上步骤,就可以在Rails应用中配置多个数据库连接,并在不同的模型中使用不同的数据库连接。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。