gpt4 book ai didi

mysql - Rails Mysql2::错误表不存在创建新迁移时

转载 作者:行者123 更新时间:2023-11-29 10:18:14 25 4
gpt4 key购买 nike

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

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 表的源。

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

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

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

Rails 版本 4.2.5
SQL版本5.7

最佳答案

请记住,您的 Source.all.map{ |source| source.name } 将在加载 Property 类时执行。此时,Source 类可能未正确初始化,并且可能未设置正确的数据库连接。此外,您只能访问 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 表。

此外,我不认为您在迁移中会看到错误。也许您正在迁移中使用模型,这是应该避免的。

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

关于mysql - Rails Mysql2::错误表不存在创建新迁移时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49786998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com