什么是Mongoid中的ActiveRecord#establish_connection?

时间:2010-09-26 13:34:25

标签: ruby-on-rails ruby database mongoid

表是一个必须以不同方式映射到不同数据库/表的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. 表格名称相同
  3. 修改
    我知道:

     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
    

1 个答案:

答案 0 :(得分:1)

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

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

在你的模特中:

set_database :secondary

您目前无法在运行时以您希望的方式交换数据库。这是在待办事项清单上,所以请留意它。