【发布时间】:2018-06-03 15:45:05
【问题描述】:
我正在使用带有 mysql2 适配器的 rails 5.1.4。
当我尝试在迁移中创建一个引用另一个表的表时,它给出的表不存在。我不明白为什么会弹出这个错误。看到一个不能帮助解决任何问题的错误是没有意义的。
我阅读了另一篇帖子 (Migration to create table raises Mysql2::Error: Table doesn't exist),提出的解决方案对我有用。我对这个解决方案感到担忧,因为它建议用“整数”替换“引用”并将“_id”添加到被引用的类名中。这使得 DB 不知道 FK 约束(从日志中执行的 mysql 可以看出)。
此外,此错误仅在少数迁移中发生。其他带有引用的迁移工作正常。
如前所述,我认为可行的解决方案并不合适。
失败的迁移代码是这样的:
class CreateLocatableEntitiesPlaceEntitiesPlaces < ActiveRecord::Migration[5.1]
def change
create_table :locatable_entities_place_entities_places do |t|
t.string :name
t.integer :type
t.references :locality, foreign_key: true, index: {:name => "index_places_on_locality_id"}
t.references :establishment, foreign_key: true, index: {:name => "index_places_on_establishment_id"}
t.references :parking, foreign_key: true, index: {:name => "index_places_on_parking_id"}
t.boolean :show_in_map
t.boolean :show_locality_name
t.date :constructed_on
t.integer :total_area
t.float :lat
t.float :long
end
end
end
还想补充一点,我已经在子文件夹中命名了我的模型,这就是我手动命名索引的原因,因为它们变得太大而无法由 MySQL 处理。以防万一它必须用它做任何事情。
以下是我的迁移文件夹的屏幕截图,其中包含所有迁移的运行顺序。
【问题讨论】:
-
我在尝试为主键为
int的表创建外键时遇到了类似的问题。由于 Rails 5 默认使用bigint作为主键和外键,而不是int,因此我必须在参考中指定type: :integer。我有点惊讶 Rails 不能自己解决这个问题……
标签: ruby-on-rails rails-migrations