0

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?

1 Answer 1

1

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
  
Sign up to request clarification or add additional context in comments.

2 Comments

Well, I did the exact same thing as you described but the problem is, I don't want to write to db1 and read to db2 I want to use db1 on some models and db2 on some models. So, when I run establish_connection(:db2) whole project connects to db2 and it brokes all my logic as you can understand.
use connects_to database: {reading: primary_db, writing: primary_db} in the model level, and also go through the documentation given in the answer It shows different solutions for your problem!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.