我正在使用带有 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 处理。以防万一它必须用它做任何事情。
下面是我的迁移文件夹的屏幕截图,其中包含所有迁移的运行顺序。
最佳答案
我意识到我的初始代码出了什么问题。在迁移中将 foreign_key 设置为 true 需要该表是可发现的。由于表名与引用文献中指定的名称不明显,因此出现此错误。
在 rails 5+ 中,您可以指定键应该引用的表名。进行此更改后,我能够毫无问题地运行迁移。
下面是更新后的代码:
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: {to_table: :base_entities_locality_entities_localities}, index: {:name => "index_places_on_locality_id"}
t.references :establishment, foreign_key: {to_table: :locatable_entities_place_entities_establishments}, index: {:name => "index_places_on_establishment_id"}
t.references :parking, foreign_key: {to_table: :locatable_entities_place_entities_parkings}, 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
正如我在问题中提到的,我为我的模型命名空间,这就是 Rails 无法自行找到的表名缺乏明显性的原因。
这篇文章有助于解决这个问题。:Specifying column name in a "references" migration
关于ruby-on-rails - rails migration 以创建一个表,在引用模型时给出 "Table doesn' t exist",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47916921/