gpt4 book ai didi

mysql - 可以在 Rails 中配置模型以从不同的数据源提取数据吗?

转载 作者:行者123 更新时间:2023-11-29 08:36:22 24 4
gpt4 key购买 nike

我们的应用程序需要从不同的数据源提取数据:一个是 MySQL 数据库,另一个是 Mongo 数据库。

是否可以配置模型从不同的数据源提取数据并利用 Rails.cache 来加快查询速度?目前,Rails 中的配置文件似乎仅支持单个数据源。

我们使用的是 Rails 3.0.6。

最佳答案

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/intializers/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

关于mysql - 可以在 Rails 中配置模型以从不同的数据源提取数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15100076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com