Rails

Connecting Models To Different Databases In Rails

Posted by Weston Ganger on March 21, 2015

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.

Heres how to set it up connecting to a different database in your Rails app.

**Note: for any joins to work correctly the databases need to be on the same server

Add database information 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
  def table_name_prefix
    # Be sure to reference the database name not the connection name
    "your_database_name#{Rails.env.production? ? '' : '_'+Rails.env}."
  end
  establish_connection "#{Rails.env}_db2"
end

For Multiple Models


### app/models/remote_models.rb
class RemoteModels < ActiveRecord::Base
  def table_name_prefix
    # Be sure to reference the database name not the connection name
    "your_database_name#{Rails.env.production? ? '' : '_'+Rails.env}."
  end
  self.abstract_class = true 
  establish_connection "#{Rails.env}_db2"
end

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

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

### app/models/company.rb
class Company < RemoteModels
end

The table_name_prefix portion is so that joins will reference the correct database. It isn’t listed in the docs for rails. Although I know it works with Rails 3.2.13. Hopefully it works with Rails 4 too.


Related External Links:


Posted in Rails and Tagged with rails multiple-databases active-record 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts