Rails Rails 4 指定第二个数据库,如何执行 migration?

yangxing_star · 2014年08月14日 · 最后由 shreadline 回复于 2014年08月14日 · 3071 次阅读

配置如下

default: &default
  adapter: mysql2
  encoding: utf8
  reconnect: false
  pool: 5
  username: root
  host: remote_ip
  port: 3306

development:
  <<: *default
  database: test

# 本地数据库
test2:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: test2
  pool: 5
  username: root
  password: 
  1. 创建数据库:rake db:create RAILS_ENV=market
  2. 表迁移:rake db:migrate SRCDIR=test2_db/migrate/ RAILS_ENV=test2 第二步出现以下问题,记得在 rails3 里面这样做是可以的 ``` config.eager_load is set to nil. Please update your config/environments/*.rb files accordingly:
  • development - set it to false
  • test - set it to false (unless you use a tool that preloads your test environment)
  • production - set it to true ```

你设置的数据库是 test2 但是再 config/environment/下面没有相应的 test2.rb 文件。我猜是这样

RAILS_ENV=production rake db:migrate 默认是 test+development

class YourMigrationFile < ActiveRecord::Migration
  def connection
    @connection ||= ActiveRecord::Base.establish_connection("custom_db_#{Rails.env}").connection
  end

  def change
    add_column :table, :column, :type
    # reset connection
    @connection = ActiveRecord::Base.establish_connection("#{Rails.env}").connection
  end
end

#3 楼 @shreadline Thanks, 那我每个 migration 都要加 connection 方法?

#1 楼 @hging 错误是缺失 config/environment/test2.rb 文件导致的,但是加入该文件,migration 也不会执行的

@yangxing_star 你需要 migrate 到 custom_db 的需要加,如果比较多可以抽取一下。正常的 migration 文件无需改动。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号