[英]Connecting to multiple databases in ruby on rails
我有一个 ruby on rails 应用程序工作正常并连接到数据库。 现在我想从同一个应用程序连接到不同的数据库。 数据模型可以完全相同。 事实上,如果我连接到不同的数据库,应用程序工作正常。 但是我想连接到两个不同的数据库。 在 ruby on rails 中可能吗?
对于多数据库连接,需要在database.yml文件中添加如下代码。 在这里,我给出了从 Rails 应用程序连接两个数据库的示例
配置/数据库.yml
development:
adapter: mysql2
database: db1_dev
username: root
password: xyz
host: localhost
development_sec:
adapter: mysql2
database: db2_dev
username: root
password: xyz
host: localhost
production:
adapter: mysql2
database: db1_prod
username: root
password: xyz
host: your-production-ip
production_sec:
adapter: mysql2
database: db2_prod
username: root
password: xyz
host: your-production-ip
这里我使用了两个数据库用于开发和生产环境。
现在我们需要将模型连接到数据库。 当您在开发和生产模式下运行应用程序时,所有模型都将通过 database.yml 中提到的开发和生产数据库参数进行映射。 所以对于某些模型,我们需要连接到其他数据库。
让我们假设,我们有两个模型 User 和 Category。 用户表在 db1_dev 和 db1_prod 中,类别表在 db2_dev 和 db2_prod 中。
品类模型
class Category < ActiveRecord::Base
establish_connection "#{Rails.env}_sec".to_sym
end
同样,当你为第二个数据库添加新的迁移时,需要添加以下代码。
class CreateRewards < ActiveRecord::Migration
def connection
ActiveRecord::Base.establish_connection("#{Rails.env}_sec".to_sym).connection
end
def change
# your code goes here.
end
end
希望它对你有用:)。
使用establish_connection
连接切换到不同的数据库:
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "myuser",
:password => "mypass",
:database => "somedatabase"
)
您还可以从 database.yml 传递预配置的环境,如下所示:
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['other_env'])
您还可以为特定模型设置它:
MyClass.establish_connection(...)
您可能要注意,从 Rails 6 (2019) 开始,Rails 支持多个主数据库!
https://guides.rubyonrails.org/active_record_multiple_databases.html
database.yml
文件现在看起来像这样:
development:
primary:
database: primary_db
user: root
primary_replica:
database: primary_db
user: ro_user
replica: true
animals:
database: my_animals_db
user: root
migrations_path: db/animals_migrate
animals_replica:
database: my_animals_db
user: ro_user
replica: true
然后就像在模型文件中指定一样简单:
class AnimalsModel < ApplicationRecord
self.abstract_class = true
connects_to database: { writing: :animals_primary, reading: :animals_replica }
end
class Dog < AnimalsModel
# connected to both the animals_primary db for writing and the animals_replica for reading
end
(这些示例取自这个有用的教程。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.