2

表是一个 Mongoid 模型,必须动态映射到不同的数据库/表

# app/models/table.rb
class Table
  include Mongoid::Document
end

# in app/controllers/some_controller.rb
def index
   Table.connection.database = :other_database # <- How to do this ???
   Table.table_name = params[:id] # <- How to do this ???
   @records = Table.all
end

我希望 Table 类:

  1. 根据当前登录的用户配置每个请求到不同的数据库(在同一个 mongodb 服务器连接上)
  2. 表名相同

编辑
我知道:

 Mongoid.configure do |config|
   name = "control_development"
   host = "localhost"
   config.master = Mongo::Connection.new.db(name)
   config.slaves = [
  Mongo::Connection.new(host, 27018, :slave_ok => true).db(name)
   ]
   config.persist_in_safe_mode = false
 end

但是,它是否适用于某些型号(?):

  # like this i mean
  class User
  include Mongoid::Document

  configure do |config| # configure only this model's connection
    name = "other_control_development"
    host = "localhost"
    config.master = Mongo::Connection.new.db(name)
    config.slaves = [
            Mongo::Connection.new(host, 27018, :slave_ok => true).db(name)
    ]
    config.persist_in_safe_mode = false
  end

 end
4

1 回答 1

1

您可以使用它连接到多个数据库。

示例配置: https ://github.com/mongoid/mongoid/blob/master/spec/config/mongoid_with_multiple_mongos.yml

在您的模型中:

set_database :secondary

您当前无法按照您想要的方式在运行时交换数据库。这在待办事项列表上,所以请留意它。

于 2011-06-07T18:32:51.153 回答