Coding active Coding active - 1 year ago 146
Ruby Question

Ruby on Rails - multiple database connections

I'm developing an application where it lets users to establish many number of database connections with a has-many relationship between user and connections. The connections are passive until the user manually connects each. The motive is to perform queries on them, parallely.

I don't find good tutorials related to this, can you help me with some tips on how to accomplish this ?

Answer Source

After researching for a bit, turns out there's a much simpler approach using ActiveRecord Connection pool.

  1. Setup a relationship between users and the database connections, in this case user 1 .. n connections.
  2. Make sure the model record can individually connect using

    obj = ActiveRecord::Base.establish_connection(...spec...) 
    obj.connection.exec_query("Select * from users") 
    # the response is in the form of ActiveResult, which allows flexible operations around the result. 
  3. Close the connection once done with the database.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download