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

标签 mysql ruby-on-rails ruby-on-rails-3 mongodb model

我们的应用程序需要从不同的数据源提取数据:一个是 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/

相关文章:

ruby-on-rails - Rails 4 belong/has_many 关系 - 删除关联属性但保留关联记录

ruby-on-rails - rails 4 中的外键

ruby-on-rails - 自定义助手的范围

scope - form_for 和作用域,rails 3

ruby-on-rails-3 - 无法在 Rails 3.2 + Rspec 2.13 下测试引擎路线

php - 需要关系数的意见

mysql - 在 bash 脚本中运行 mysql 命令,无需登录或在每个命令中添加 -u root

mysql - 根据 MySQL 中的逻辑创建新参数

MySQL:如何实现行级安全(如 Oracle 的虚拟专用数据库)?

ruby-on-rails - 在任何源中都找不到 json-1.8.1