How To Use Two Databases Into A Single Application?
How To Use Two Databases Into A Single Application?
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 }
Can you explain the difference between ActiveSupport’s HashWithIndifferentAccess and Ruby’s Hash ?
Xem chi tiếtDoes Ruby Support Single Inheritance/Multiple Inheritance Or Both?
Xem chi tiếtExplain how you define Instance Variable, Global Variable and Class Variable in Ruby?
Xem chi tiếtĐăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.