1

I have a multi-domain Rails 4 app where the request.domain of the http request determines which functionality I expose a given visitor to. A visitor can sign up through Devise. During the user creation a user.domain field will be filled in with the domain he signed up for, and he will then only have access to this particular domain and its functionality.

Question:

Each domain in my app should be served by its own MongoDB database. If user.domain == 'domain1.com' the user object, as well as all objects that belongs_to it, should be stored in the database that serves domain1.com. How do I set this up?

Complication 1:

I do not only interact with my database through Mongoid, but also through mongo Shell methods like db.collection.insert(). I need to have the correct database connection in both cases. Example:

class ApplicationController < ActionController::Base
  before_filter :connect_to_db
  def connect_to_db
    domain = request.domain
    # Establish connection
  end
end

Complication 2:

A lot of the database interaction happens outside the MVC context. I need to have the correct database connection in e.g. a Sidekiq context. Example:

class MyJob
  include Sidekiq::Worker
  def perform(domain)
    connect_to_db(domain)
    User.all.each do |user|
      ...
    end
  end

  def connect_to_db(domain)
    # Establish connection
  end
end

Potentially relevant SO answers:

This answer and this answer suggests that you can apply a set_database or store_in session method on a model level, but this would not be sufficient for me, because models are shared between my domains. Various stragegies have also been discussed in this Google group.

Community
  • 1
  • 1
Cjoerg
  • 1,271
  • 3
  • 21
  • 63

0 Answers0