【发布时间】:2015-08-15 19:01:09
【问题描述】:
在我的 Rails 多租户应用程序中,我使用多个数据库,并使用 ActiveRecord::Base.establish_connection(tenant_config) 从一个数据库切换到另一个数据库,这很好。
如何处理 rufus-scheduler 中的多个连接?我必须在每个调度程序中迭代连接吗?
#not work
scheduler.every '1h' do
MyModel.create(title: "test")
end
可能是这样的:
scheduler.every '1h' do
active_records_all_connections.each do
MyModel.create(title: "test")
end
end
有人可以帮助我提供更好的解决方案或建议。 谢谢。
我使用此代码来管理我的多个数据库连接
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
【问题讨论】:
标签: ruby-on-rails ruby rufus-scheduler