2013-02-19 37 views
2

我有一个运行在Unicorn上的Sinatra应用程序,它使用Mongoid作为它的模型。我有几个结构相同但内容不同的Mongo数据库,我为每个用户在他/她登录时选择正确的数据库。我想知道Mongoid 3.0是否可以这样做。在运行时在Mongoid 3.0中切换数据库

回答

3

您可以查询每次使用前with操作:

Model.with(database: method_to_get_the_db_name).create 
2

如果你想切换数据库,使用Mongoid.override_database,它是线程安全的。

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

实施例:

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 

文档可以发现here