Rails Mysql2::Error Table 不存在 创建新迁移时

Rails Mysql2::Error Table doesn't exist When create new migration

我用以下内容编写了一个迁移(创建名为 sources 的新 table):

class CreateSources < ActiveRecord::Migration
  def change
    create_table :sources do |t|
      t.string :name, null: false, default: ""

      t.timestamps null: false
    end
  end
end

然后我修改了我现有的模型:

class Property < ActiveRecord::Base
  validates :source, allow_blank: true, inclusion: { in: 
  Source.all.map{ |source| source.name } }

我想对 属性 的来源添加验证以仅允许来自 sources table.

的来源

然后当我 运行 迁移时,出现以下错误:

ActiveRecord::StatementInvalid: Mysql2::Error: Table 'sources' doesn't exist: SELECT `sources`.* FROM `sources`

问题是源 table 的查询在尚未初始化时发生。
关于如何迁移到 运行 的任何提示?
这是生产级别的运行。所以我可能不能放弃所有迁移并重新安排它。

Rails 版本 4.2.5
SQL 版本 5.7

Have you defined Source model? I hope so.

Here the problem looks like the loading of Property class takes priority before migration is run and hence the issue.

请记住,您的 Source.all.map{ |source| source.name } 将在 Property class 加载时执行。此时 Source class 可能未正确初始化,并且可能没有正确设置数据库连接。此外,您将只能访问 Source.all 一次,因此如果您添加了新的 Source.

,则必须重新启动您的应用程序

改为手动验证:

class Property < ActiveRecord::Base
  validate :valid_source
private
  def valid_source
    return if(source.blank?)
    return if(Source.where(name: source).exists?)
    errors.add(:source, 'Unknown source') # Or whatever you want to say
  end
end

这样您就可以在正确的时间检查 sources table。

此外,我不希望您看到的错误发生在迁移过程中。也许您正在迁移中使用模型,这是要避免的。

顺便说一句,您没有 belongs_to :source 有什么特别的原因吗?像这样复制名称很容易出错,使用引用(希望由数据库中的外键支持)会更安全。