在Mongoid 3.0中运行时切换数据库

时间:2013-02-19 17:33:46

标签: mongodb mongoid

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

3 个答案:

答案 0 :(得分:3)

您可以在每次查询之前使用with运算符:

Model.with(database: method_to_get_the_db_name).create

答案 1 :(得分:3)

如果要切换数据库,请使用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

答案 2 :(得分:0)

mongoid-dynamic-clients宝石。

我也有自己的Mongoid 5帮助器方法,该方法使用默认连接但数据库名称不同:

  def within_database(name)
    previous_client = Mongoid::Threaded.client_override
    unless Mongoid::Config.clients[name].present?
      Mongoid.clients[name] = Mongoid::Config.clients[:default].dup
      Mongoid.clients[name][:database] = name
      Mongoid::Config.clients[name][:__instance] = Mongoid::Clients::Factory::create(name)
    end

    Mongoid.override_client(name)

    yield Mongoid::Config.clients[name][:__instance]

    Mongoid.override_client(previous_client)
  end

用法:

within_database('my_different_database') do |connection|
  puts "Current database: #{connection.database.name}"
  Model.all.length
  # Or you may even drop it by using the connection object
  connection.database.drop
end
相关问题