Skip to content

Instantly share code, notes, and snippets.

@geekdreamzz
Last active December 22, 2015 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geekdreamzz/6533426 to your computer and use it in GitHub Desktop.
Save geekdreamzz/6533426 to your computer and use it in GitHub Desktop.
Is there a legitimate use case where a system may contain multiple database? What if you have many applications but want a centralized user database that is accessible to your numerous apps that also have a hefty database schema of its own? Here's a possible solution that is very easy to implement, what do you think? 1. Add new database connecti…
#Add multiple databases to a Rails App
#given you have other database connections you'd like to define inside the rails app
#Here's a possible solution to define multiple databases
#do not copy this template over your current configuration
#just add/name the connection and add _staging or _production (whichever environment the DB is for)
#to the current database.yml
#imagine we have a seperate database that manages members
#these members have access to this app, and 10 other apps you / your start-up ;) has developed.
#so the members database is separate and here we make members accessible to this app.
#once this is added you can create a Class with this established connection.
members_development:
adapter:
encoding:
reconnect:
database:
pool:
username:
password:
host:
port:
socket:
members_production:
adapter:
encoding:
reconnect:
database:
pool:
username:
password:
host:
port:
socket:
#below are default db settings for the app, you can put the external databases above or below.
#I'd put it at the bottom of the yaml, but for this example I put it up top so you could see it first.
development:
adapter:
encoding:
pool:
database:
username:
password:
host:
port:
test:
adapter:
encoding:
reconnect:
database:
pool:
username:
password:
host:
socket:
production:
adapter:
encoding:
pool:
database:
username:
password:
host:
port:
class Member < ActiveRecord::Base
establish_connection "members_#{Rails.env}"
#now that you are connected you can add associations
#your database is seperate because "members" database manages about "10 other" apps with thier own database
#nonetheless, rails internally does the data mapping inside the application itself and we just need
#to update our routes.rb to nest these resources
has_many :post, dependent: :destroy
has_many :comment, dependent: :destroys
end
#for mapping and active relations update your routes
#so the rails app can know the relationships between the
#different tables even when in a different database
thenextbigthing::Application.routes.draw do
resources :members do
resources :posts do
resources :comments
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment