How To Use Two Databases ...
How To Use Two Databases ...
Using two databases in a single Ruby on Rails application can be achieved by configuring multiple database connections. This is useful for scenarios where you need to separate different types of data or interact with legacy systems. Here’s a step-by-step guide on how to set this up:
First, you need to define the connections in your config/database.yml
file. Here’s an example configuration:
default: &default
adapter: postgresql
encoding: unicode
pool: 5
development:
primary:
<<: *default
database: primary_db
secondary:
<<: *default
database: secondary_db
test:
primary:
<<: *default
database: primary_db_test
secondary:
<<: *default
database: secondary_db_test
production:
primary:
<<: *default
database: primary_db_production
secondary:
<<: *default
database: secondary_db_production
Next, you need to tell your models which database to use. By default, models use the primary
database. For models that should use the secondary
database, you can specify the connection like this:
class SecondaryBase < ApplicationRecord
self.abstract_class = true
connects_to database: { writing: :secondary, reading: :secondary }
end
class SecondaryModel < SecondaryBase
# Your model code here
end
Rails supports running migrations for multiple databases. You can specify which database to ...
expert
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào