我使用rails 5.1.4与mysql2适配器。
当我尝试在迁移中创建一个引用另一个表的表时,它表不存在。我不明白为什么会弹出这个错误。看到一个无法帮助解决问题的错误毫无意义。
我读了另一篇文章(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处理。以防它必须对它做任何事情。
下面是我的迁移文件夹的屏幕截图,其中包含所有迁移,以便它们运行。
它是关于迁移文件的顺序是在`db / migrate'文件夹中。
如果含有migration-file
的table
的Foreign Key
在Parent Table
之前执行,它会引发table not found
错误
在您的情况下,应首先迁移下表的迁移
index_places_on_locality , index_places_on_establishment, index_places_on_parking
然后是CreateLocatableEntitiesPlaceEntitiesPlaces
表。
检查`db / migrate'文件夹中的订单
迁移文件将以当前日期和时间命名。所以它会按照那个顺序执行。请参阅Running Migrations
我意识到我的初始代码出了什么问题。在迁移中将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
正如我在问题中提到的那样,我将模型命名为间隔,这就是导轨无法找到的表名缺乏明显性的原因。
这篇文章帮助解决了这个问题:Specifying column name in a "references" migration