【问题标题】:Rails 4.1.1 Postgres app with Mysql Legacy database ImportRails 4.1.1 Postgres 应用程序与 Mysql Legacy 数据库导入
【发布时间】: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


【解决方案1】:

你可以尝试在 subclass.import 前加上 ::

def self.import_all
  Rails.application.eager_load!
  self.subclasses.each {|subclass| ::subclass.import }
end

【讨论】:

  • 没有骰子,当类是变量时,您似乎无法将 :: 前缀添加到类中,例如 ::subclass.import。我只是收到一个错误:syntax error, unexpected tIDENTIFIER, expecting tCONSTANT self.subclasses.each {|subclass| ::subclass.import }。我想知道是否应该在所有使用它的模型中添加:: 而不是constantize
  • 试试Kernel.const_get("#{subclass}").import
  • 没有骰子,同样的错误。唔。我觉得池中的连接可能太多?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-01
  • 2012-04-28
相关资源
最近更新 更多