1

is it possible to use 2 types of database in a Rails application?

I am using 2 databases - Postgres to store data which might not change much, and MongoDB to store data which change dynamically.

is this valid approach? and is it possible to connect between these 2 databases and operate in a single Rails application?

Please correct, if i am wrong.

regards, Balan

balanv
  • 10,686
  • 27
  • 91
  • 137
  • Probably related to http://stackoverflow.com/questions/1825844/multiple-databases-in-rails – waldyr.ar Dec 31 '12 at 11:32
  • By searching web i found a solution http://stackoverflow.com/questions/1825844/multiple-databases-in-rails but the note specified mentions like sticking to single database first and establishing connection to second one using adapter.. but what i am trying is to have these 2 db configured in the Rails app so that i can do normal process like creating table with migration, updating table with Model etc., – balanv Dec 31 '12 at 11:32
  • so are you saying this approach is not right? if so you can add this note in answer with relevant references. – balanv Jan 02 '13 at 06:42
  • Yes, I have done this and it is quite straightforward. – B Seven Sep 22 '19 at 17:57

2 Answers2

0

yes this is possible here is an example from my old code (but here we use mysql for both the DB, but I think you can get an idea)

in database.yml file define two databases

development: &defaults
  adapter: mysql
  encoding: utf8
  database: DB1
  enable_call: true
  username: 
  password: 
  host: 

portal_development: &defaults
  adapter: mysql
  encoding: utf8
  database: DB2
  enable_call: true
  username: 
  password: 
  host: 

in your models have to base models coupled with above databases

portal_base.rb

class PortalBase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "portal_#{Rails.env}"

  def self.table_name_prefix
    "DB1."
  end
end

default_base.rb

class DefaultBase < ActiveRecord::Base

  self.abstract_class = true

  establish_connection "#{Rails.env}"

  def self.table_name_prefix
    "DB2."
  end

end

and derive your models accordingly

class Client < PortalBase
  #code
end

Hope you have an idea now :)

sameera207
  • 16,547
  • 19
  • 87
  • 152
0

Found solution :

We can use mongoid gem to achieve this.

Steps to install

1) Install mongoid by adding "gem mongoid" in Gemfile and running bundle command

2) Generate mongoid configuration by typing "rails g mongoid:config", this will create a config file mongoid.yml near database.yml file, you can add the configuration to Mongo server in this file.

Note : After adding Mongoid, all the models created will be created for MongoDB by default, you can specify --orm option to generate Models for Postgres.

balanv
  • 10,686
  • 27
  • 91
  • 137