ruby-on-rails - Mongoid 中 ActiveRecord#establish_connection 的等价物是什么?

标签 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. 表名相同

编辑
我知道:

 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

最佳答案

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

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

在你的模型中:

set_database :secondary

您目前不能按照您想要的方式在运行时交换数据库。不过,这在待办事项列表中,因此请密切关注它。

关于ruby-on-rails - Mongoid 中 ActiveRecord#establish_connection 的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3798003/

相关文章:

ruby-on-rails - rails :dependent and :delete

ruby-on-rails - 回形针直接通过网址获取图像

ruby-on-rails - 将有效载荷随机数提交到服务器 Braintree SDK Paypal ruby​​ rails

javascript - javascript推荐的数据库缓存库

mysql - 选择不起作用后删除

ruby-on-rails - Rails 4如何使用带有其他text_field的复选框集合来建模表单

ruby-on-rails - Zeus 在使用 Rspec 进行测试时失败

ruby-on-rails - ActiveRecord::RecordInvalid 验证失败:帐户必须存在

ruby-on-rails - 如何修复和测试 Rails 4 模型中的竞争条件

python - 根据另一个类在 django 中动态加载特定应用程序的最佳方法是什么?