How do I quickly switch between multiple DBs in rails?

Asked 3 months ago, Updated 3 months ago, 9 views

Environment: ruby 2.1.3, rails 4.2, activaterecord-sqlserver-adapter 4.1

If you have to switch from place to place to place to process 20 databases.
First, prepare an array (specs) containing connection information and do|x|
  100.times {{ActiveRecord::Base.establish_connection(specs.sample)}}

I checked and found out.It seems to take 0.9 to 1.2 seconds.
Regardless of the cost of a single unit, first keep all the connections and
Would it be possible to reduce the switching cost by changing only where the query is thrown?

Here's what I'm thinking:
(I also thought about creating a DB connection model and inheriting each model.I also find it strange to make 20 copies of each model file.I thought about dynamically replicating and re-inheriting the model, but I want to use it as a last resort.and)

ruby-on-rails rails-activerecord

2022-09-30 12:01

1 Answers

I've never actually done it myself, and there are some differences from the situation you asked, but I thought the content of this page was quite close.

Code quoted from the above article

#A model class that connections to a different DB depending on the subdomain 
# we're in
class ModelBase<ActiveRecord::Base
  self.abstract_class = true

# ...

  def initialize

  # Override the behavior of ActiveRecord's ConnectionHandler to return a
  # connection pool for the current domain.
    # Get current subdomain somehow (Maybe store it in a class variable on) 
    # each request or whatver)
    [email protected]@subdomain
    @ pools_by_subdomain [subdomain]||=create_pool(subdomain)

  def create_pool(subdomain)
    conf=Rails.configuration.database_configuration [Rails.env].dup
    # The name of the DB for that subdomain...
    # Call ConnectionHandler #establish_connection, which receipts a key 
    # (in this case the subdomain) for the new connection pool

The original article requires that the connection be changed according to the subdomain, and the connection is switched within the retrieve_connection_pool method.

If you change this area to fit your requirements, you may be able to achieve your goal.

That's all for your information.

2022-09-30 12:01

If you have any answers or tips

© 2023 OneMinuteCode. All rights reserved.