I'm developing a rails application in which each subdomain has a separate database. And I'm doing something like this.
#app/controller/application_controller.rb
class ApplicationController < ActionController::Base
before_filter :select_database
private
def select_database
MyModel.use_database(request.subdomains.first)
end
end
#app/model/my_model.rb
class MyModel < ActiveRecord::Base
def self.use_database path
establish_connection :adapter => 'sqlite3', :database =>
File.join(RAILS_ROOT, "db", "sqlite3", path)
end
end
Now, in production
mode, requests come and execute in this order.
- Request "A" comes for subdomain a.example.net and
MyModel
establishes a connection with database "a". - Now another request "B" comes for subdomain b.example.net and
MyModel
establishes a connection with database "b". - Now if request "A" tries to do a
MyModel.find_*()
which database would it access? "a" or "b"?
I believe that this is what we call "thread safety" or "race condition", and if this is so, then how can we avoid it while implementing an application using one database per subdomain?
In the above question, my assumption is that executing two requests simultaneously is a normal behaviour for production servers. Or is there some better approach. I don't have much experience of production servers, so please advice.