Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching databases at runtime in Mongoid 3.0

I have a Sinatra application running on Unicorn that uses Mongoid for its models. I have several Mongo databases with the same structure but different content, and I to select the right database for each user when he/she logs in. I am wondering if this is possible with Mongoid 3.0.

like image 672
user2398029 Avatar asked Sep 05 '25 03:09

user2398029


1 Answers

If you want to switch database, use Mongoid.override_database, it's Thread safe.

Mongoid.override_database("client_db_name") # change the database Mongoid.override_database(nil) # reset the database

Example:

class ApplicationController < ActionController::Base
  before_filter :switch_database
  after_filter :reset_database

  private

  def switch_database
    client_ref = params[:client_id]
    Mongoid.override_database("my_db_name_#{client_ref}")
  end

  def reset_database
    Mongoid.override_database(nil)
  end
end

Documentation can be found here.

like image 181
Aymeric Avatar answered Sep 09 '25 01:09

Aymeric