Search code examples
ruby-on-railsrubyrufus-scheduler

rufus-scheduler and multiple databases connections


In my rails multi-tenant application, I use multiple databases and I switch from one to another using ActiveRecord::Base.establish_connection(tenant_config), this work fine. how to handle this multiple connections in rufus-scheduler ? Do I have to iterate connections in each scheduler ?

#not work
scheduler.every '1h' do
    MyModel.create(title: "test")
end

maybe like this :

scheduler.every '1h' do
    active_records_all_connections.each do
      MyModel.create(title: "test")
    end
end

can someone help me with a better solution or an advise. Thx.

I use this code to manage my multiple db connections

module DatabaseSwitching

  def choose_database_from_tenant(tenant)
    unless defined? @@_client_database_details
      @@_client_database_details = Hash.new
    end
    if @@_client_database_details[tenant].nil?
      @@_client_database_details[tenant] = fetch_tenant_database_for tenant
    end
    connect_to_database_for @@_client_database_details[tenant]

  end

  def fetch_tenant_database_for(tenant)
    file_path = "#{Rails.root}/config/databases/database.yml"
    raise ActionController::RoutingError.new('Not Found') unless tenant
    tenant_db = "database_" + tenant

    if @file_to_load != File.ctime(file_path)
      @details = YAML.load_file(file_path)[tenant_db]
      @file_to_load = File.ctime(file_path)
      raise ActionController::RoutingError.new('Not Found') unless @details
    end
    @details
  end


  def connect_to_database_for(details)
    ActiveRecord::Base.establish_connection(details)
 end
end

Solution

  • Lambi says:

    In my rails multi-tenant application, I use multiple databases and I switch from one to another using ActiveRecord::Base.establish_connection(tenant_config)

    So, simply do something like:

    scheduler.every '1h' do
      ActiveRecord::Base.establish_connection(tconfig0)
      MyModel.create(title: "test for tenant0")
    end
    scheduler.every '1h' do
      ActiveRecord::Base.establish_connection(tconfig1)
      MyModel.create(title: "test for tenant1")
    end
    

    You switch with .establish_connection in your regular code, why not using it in your scheduled jobs?

    Please note that rufus-scheduler does not give a damn about Rails or Active Record or database connections, it just uses threads to get its scheduling work done. No magic.