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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With