I created two rails apps sample
and test
. There are two databases. users
table in sample
app with the field report_id
refers to reports
table in test
app.
I want to display the test
app data in sample
app by fetching the unique_id
field. I want to display reports
data for a particular user by connecting these two databases.
How can I achieve this in the simplest way?
答案 0 :(得分:1)
对于rails6,您可以提供两个连接并为每个连接指定数据库, 例如
adapter: postgresql
encoding: unicode
username: username
password: password
pool: 5
host: localhost
development:
primary:
<<: *default
database: database1
adapter: postgresql
secondary:
<<: *default
database: database2
adapter: postgresql
在生产环境中,您可以使用数据库url之类的
primary:
url: <%= ENV['DATABASE_URL'] %>
secondary:
url: <%= ENV['SECONDARY_DATABASE_URL'] %>
答案 1 :(得分:0)
You can connect to two databases from each rails project:
#config/sabple_database.yml
default: &default
encoding: utf8
adapter: mysql2
port: 5500
development:
<<: *default
database: sample_db
host:
username:
password:
#config/initializers/sample_database.rb
SAMPLE_DB = YAML.load_file(File.join(Rails.root, "config", "sample_database.yml"))[Rails.env.to_s]
#models
class SampleDbBase < ActiveRecord::Base
self.abstract_class = true
establish_connection SAMPLE_DB
end
#models/my_model.rb
class MyModel < SampleDbBase
end
Read more about that. So, then you can create the same models without migration(allows using Reports.find(report_id)
).
Also, you can write a query to some database using ActiveRecord::Base.establish_connection
and execute
.
答案 2 :(得分:0)
感谢rails 6. rails 6将默认提供多数据库连接。 请使用GitHub版本的rails。并配置数据库。yml:
development:
primary:
<<: *default
database: multiple_databases_development
animals:
<<: *default
database: multiple_databases_development_animals
migrations_paths: "db/animals_migrate"
有关更多详细信息,请查看https://github.com/eileencodes/multiple_databases_demo