设置默认数据库连接Rails

时间:2012-06-26 17:46:23

标签: ruby-on-rails database activerecord mongoid

我的rails应用程序有自己的MySql数据库(并且需要mysql2 gem),但是还需要为一个特定模型连接外部MongoDB数据库(因此我在Gemfile中包含了mongoid和bson_ext)。现在,当我尝试为新模型生成迁移时,它告诉我

$ rails g migration CreateLocations
       error  mongoid [not found]

当我生成Location模型时,它包含Mongoid :: Document,因此Rails显然认为它使用外部数据库作为我的主数据存储区。

databse.yml:

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: associalize_development
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock

mongoid.yml:

development:
  host: pearl.mongohq.com
  port: 27019
  username: asfasdf
  password: sadfasdf
  database: app4574678

test:
  host: pearl.mongohq.com
  port: 27019
  username: asdfadhasdfa
  password: hadsadfas
  database: app4574678

production:
  host: pearl.mongohq.com
  port: 27019
  username: asdfdfsasda
  password: afdasdfdasdf
  database: app4574678

更新  使用Mongo的模型

class ExternalMongoModel
  include Mongoid::Document

  field :title
  field :long_title
  field :deal_type
  field :merchandise_type
  field :market_id
  field :market_name
  field :market_location, type: Array
  field :featureType
  field :country_code
  field :subtitle
  field :offer_ends_at
  field :price
  field :value
  field :merchant_type
  field :content
  field :merchant

  index(
    [[:division_latlon, Mongo::GEO2D]], background: true
  )

end

3 个答案:

答案 0 :(得分:27)

将其添加到config / application.rb中的Application块:

config.generators do |g|
  g.orm :active_record
end

(找到解决方案here

答案 1 :(得分:19)

如果您不想更改config / application.rb,可以在生成模型时使用它:

rails generate active_record:migration

如果更改application.rb文件,要调用mongoid生成器,比如模型“contacts”,可以使用:

rails g mongoid:model contacts

solution link

答案 2 :(得分:4)

首先检查以下块是否存在于rails应用程序的config / application.rb文件中

config.generators do |g|
  g.orm :active_record
end

如果没有添加,或者你可以运行

rails g active_record:migration