Rails 提供了使用多个数据库的约定。让我向您展示如何使用 Mango 和 Mysql。
将 mysql 视为主数据库。所以mysql的配置进入config/database.yml
config/database.yml
development:
#dev config goes here
test:
#test config goes here
production:
#production config goes here
现在考虑 Mongo。在 config/mongo_database.yml 中为 Mongo 放置另一个配置
config/mongo_database.yml
development:
#dev config goes here
test:
#test config goes here
production:
#production config goes here
现在我们将用户模型连接到mysql:
class User < ActiveRecord::Base
#Active record by default connects with the primary database configuration
end
现在我们将 Product 模型连接到 Mongo:
class Product
include MongoMapper::Document
end
你还需要在 config/initializers/mongo.rb 中初始化 mongo 设置
config/intializers/mongo.rb
Mongoid.configure do |config|
config = YAML.load_file(Rails.root.join("config", "mongo_database.yml"))[Rails.env]
host = config["host"]
config.master = Mongo::Connection.new.db(config["database"])
end