my project require connecting to multiple databases within a rails project. The database information is not known in advance, so including the database information in config/database.yml
is not an option. Here is my code to solve this :
mclass ConnectionManager
@@connections_map = nil
def self.create_connection(klass_name,database_params)
@@connections_map[klass_name] = Class.new(ActiveRecord::Base) do |c|
#c.abstract_class = true
c.establish_connection(database_params)
end
end
def self.connections
@@connections_map = {} unless @@connections_map.present?
mydata = MyModel.where(.....)
mydata.each do |data|
klass_name = data.name.camelcase
create_connection(klass_name,data.database_params) unless @@connections_map[klass_name]
end
@@connections_map
end
end
Now ideally I should be able to call ConnectionManager.connections
which should return class objects with appropriate database connections.
But the problem is all the newly created class have the same connection information. The last connection created is getting overwritten to all the previous class objects.
What is wrong with this approach ?