【发布时间】:2014-05-16 04:52:48
【问题描述】:
我一直在使用 postgres 数据库构建一个 Rails 应用程序,但当然我还负责从旧版 mysql 数据库导入数据。
到目前为止我处理这个问题的方式:
# config/database.yml
development:
adapter: postgresql
encoding: unicode
database: myapp_development
pool: 10
username: myuser
password:
legacy_development:
adapter: mysql2
encoding: utf8
reconnect: false
database: myapp_legacy
pool: 10
username: myuser
password:
socket: /tmp/mysql.sock
# app/models/legacy.rb
class Legacy < ActiveRecord::Base
self.abstract_class = true
establish_connection "legacy_#{Rails.env}".to_sym
def self.import
self.find_each do |object|
imported_model = object.class.model.new object.attribute_map
object.report_failures unless imported_model.save
end
end
def self.import_all
Rails.application.eager_load!
self.subclasses.each {|subclass| subclass.import }
end
end
# app/models/legacy/chapter.rb
# a bunch of different subclasses like this
class Legacy::Chapter < Legacy
self.table_name = 'chapters'
def self.model
'Chapter'.constantize
end
def attribute_map
{
id: id,
name: name,
body: chapterBody
}
end
end
然后我有一个运行 Legacy.import_all 的 rake 任务。其中很多是从this post 窃取的。
这里有一些问题:
主要问题是,当我运行 Legacy.import_all 时,它会通过大约一半的表,然后我收到如下错误:
NoMethodError: undefined method 'import' for Legacy::SomeSubclass(Table doesn't exist):Class
我认为这是因为池中的连接太多。看起来虽然它正在从 postgres 数据库中寻找 SomeSubClass table_name,但它应该在 mysql 数据库中寻找。
这可能是因为以下方法:
def self.model
'Chapter'.constantize
end
在上面的子类中。我是这样做的,而不是:
def self.model
Chapter
end
因为我的应用中有一个普通模型(非旧版),也称为 Chapter,而且我也遇到了范围界定问题。
无论如何,这是一个巨大的混乱,任何关于我应该在哪里挖掘的想法将不胜感激。
谢谢
【问题讨论】:
-
我猜想与 Legacy 类和 Legacy 模块的同名相关的东西
标签: mysql ruby-on-rails ruby postgresql activerecord