Reputation: 333
Well, I have been reading a lot about this online but I could not solve the problem I face with.
What I want is being able to fetch and store data from multiple DB's from one Rails project. But the problem is, when I create another model for another DB such like user_db_1.rb and user_db_2.rb, when establish_connection
method under user_db_2.rb is triggered, all my project starts fetching data from db_2. I want all my models to run on primary database except I set something custom to fetch and save data from db_2.
What is the correct way of implementing this on Ruby on Rails?
Upvotes: 0
Views: 126
Reputation: 1689
Rails version 6.x supports reading and updating records from/to multiple databases.
Following this, link will be useful
We have to explicitly specify to which database needed to be used on model level.
class PrimaryModel < ApplicationRecord
connects_to database: {
writing: :primary_db,
reading: :secondary_db
}
end
The respective database configuration, database.yml
would be
production:
primary_db:
database: prima_database
username: root
password: <%= ENV['ROOT_PASSWORD'] %>
adapter: mysql2
secondary_db:
database: sec_database
username: root
password: <%= ENV['ROOT_READONLY_PASSWORD'] %>
adapter: mysql2
replica: false
Upvotes: 1