1

I use multible databases with ActiveRecord. I must put establish_connection db in all models. But i want to call the connection of libraries file. While put establish_connection db in for all models Database connection count is too much . How can I do other methods?

My project is a Ruby on Sinatra.

sozgur
  • 21
  • 4

2 Answers2

0

Build a global hash of {db_name => connection_instance } for all possible connections you have and retrieve them from your models intelligently:

def get_or_establish_connection db
  $connections[db] ||= establish_connection db
end

That way you’ll reuse all already established connections.

NB I wrote “global” because there is no way to suggest anything more robust without knowledge of your architecture details. In the real life one would put this hash as a class variable somewhere accessible from everywhere.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
0

What we did in our projects that used multiple databases was creating one class per database, that establish the connection, and make models inherit from it. That way, only one connection is created per database.

class UsageTable < ActiveRecord::Base
  self.abstract_class = true
  establish_connection :usage
end
class User < UsageTable
user3033467
  • 1,078
  • 15
  • 24