I had some models that were being used in quite a few different applications, so we needed to move them into their own application and database. I found out a nice way of doing this and wanted to share the solution to set up models that connect to a different database in your Rails app.

Add the information about your other database(s) to your config/database.yml like so:


### config/database.yml
development:
  ...
test:
  ...
production:
  ...
development_db2:
  database: your_database_name_development
  ...
test_db2:
  database: your_database_name_test
  ...
production_db2:
  database: your_database_name
  ...

For a Single Model


class Site < ActiveRecord::Base
    self.table_name_prefix =  "your_database_name#{Rails.env.production? ? '' : '_'+Rails.env}."
  
    establish_connection "#{Rails.env}_db2"
end

For Multiple Models


### app/models/remote_models.rb
class SecondDatabaseModels < ActiveRecord::Base
    self.abstract_class = true 

    self.table_name_prefix =  "your_database_name#{Rails.env.production? ? '' : '_'+Rails.env}."
  
    establish_connection "#{Rails.env}_db2"
end

### app/models/site.rb
class Site < SecondDatabaseModels
end

### app/models/project.rb
class Project < SecondDatabaseModels
end

### app/models/company.rb
class Company < SecondDatabaseModels
    ### In some cases where the joins are complicated you may need to add the following 
    ### because Rails might incorrectly ignore the table_name_prefix    
    self.table_name =  "your_database_name#{Rails.env.production? ? '' : '_'+Rails.env}.companies"
end


Related External Links: