1

I have a problem where I have 2 associated models which are stored in separate databases on the same server.

Say I have two models, City and SportsTeam. I want to be able to find all the sports teams which are nfl teams, and then get their associated cities. I have run into a lot of trouble trying to do this since they are located on separate dbs.

class City
    eastablish_connection :city_db
    has_one :sports_team
end

class SportsTeam
    belongs_to :city
    validates :is_nfl_team, :is_mlb_team, :is_nhl_team, presence: true
end
Mitch Kerr
  • 13
  • 4
  • 1
    Possible duplicate of https://stackoverflow.com/questions/46495427/is-it-possible-to-inner-join-across-multiple-databases-in-rails – Josh Brody Sep 27 '19 at 21:32

1 Answers1

0

In Rails 5 it's possible, but I would recommend upgrading your app to Rails 6 since you are using multiple databases and Rails 6 support this feature natively.

In Rails 5

  1. You can define another database configuration file, for example, second_database.yml inside the config folder and then load it in an initializer like this: SECOND_DATABASE = YAML::load(ERB.new(File.read(Rails.root.join('config','second_database.yml'))).result)[Rails.env]

  2. Then inside of the models (which its records are in the second database) include this: establish_connection SECOND_DATABASE

Keep in mind that I've worked with multiple databases in Rails 5 and you may run into problems, but what you are trying to do is entirely doable.

In Rails 6

A much better option is to upgrade to Rails 6 and use its multiple database feature, basically what you have to do is:

  1. Define both databases connection inside database.yml.
  2. Add connect_to(:database_one), connect_to(:database_two), etc. at the models depending where their data are.

More details at: https://guides.rubyonrails.org/active_record_multiple_databases.html

Patricio Sard
  • 2,092
  • 3
  • 22
  • 52