表是一个 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 类:
- 根据当前登录的用户,将每个请求配置到不同的数据库(在同一个 mongodb 服务器连接上)
- 表名相同
编辑
我知道:
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/