我有以下表格:
- Route(ID, Name),主键为ID
- Stop(ID, Name),主键为ID
- Mapping(Route_ID, Stop_ID)
在我的Mysql-DB中,Route和Stop的ID类型为BIGINT(20)。迁移失败,因为使用了以下代码:
class CreateMappings < ActiveRecord::Migration
def change
create_table :mappings do |t|
t.references :route, index: true, foreign_key: true
t.references :stop, index: true, foreign_key: true
t.timestamps null: false
end
end
end
创建一个名为Mappings的表,其中包含route_id和stop_id两个字段,但数据类型为INT(11),这与BIGINT(20)不兼容。我该怎么办?有什么想法吗?创建外键失败。
错误信息:
这是
rake db:migrate --trace
输出的一部分:** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment ** Invoke db:load_config (first_time) ** Execute db:load_config ** Execute db:migrate == 20151227194101 CreateMappings: migrating =================================== -- create_table(:mappings) rake aborted! StandardError: An error has occurred, all later migrations canceled:
Mysql2::Error: Cannot add foreign key constraint: ALTER TABLE
mappings
ADD CONSTRAINT fk_rails_1b9f715271
FOREIGN KEY (route_id
) REFERENCES routes
(id
)当我尝试使用MySql-Client执行上述SQL语句(ALTER TABLE
mappings
...)时,我会收到此错误:Failed to add the foreign key constaint. MIssing index for constraint 'fk_rails_1b9f715271' in the referenced table 'routes'.