Rails + Devise + CouchDB with one database per subdomain

I am creating an application that requires CouchDB synchronization.

So, for each "account" in the service, I want to create a separate instance of the CouchDB database to synchronize only this account data.

I use CouchRest Model and Devise, which handles subdomain authentication through a separate user database.

However, what is the correct way to connect to the appropriate runtime database for each model?

A before_filter, which establishes a named connection, then iterates over each model and does something like this :?

[Post, Tag, Comment].each do |model| model_server = CouchRest::Server.new(couch_config[:connection]) model_server.default_database = "my_project-#{Rails.env}-#{model.to_s.downcase}" model.database = model_server.default_database end 

(pseudo code)

Assuming that the web server (Heroku) runs each request in a separate thread, this should mean that with each request, the database connection changes dynamically.

It seems like there should be an easier way!

+4
source share
1 answer

As a solution to the question, you can override the database method:

 class OneDbPerAccountDocument < CouchRest::ExtendedDocument def self.database Account.current_database end ... end 

And then just subclasses of your models (Post, Tag, Comment) from this class.

 class Account < OneDbPerAccountDocument def self.current=(name) @current_database = @couch_server.database("my-project_#{name}") end def self.current_database @current_database end end 

With this trick, all you have to do in the controller is to simply call something like

  Account.current = request.subdomain 

But be careful that this approach becomes a little dirty if you have several thousand accounts (databases).

+4
source

All Articles