首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Rails: Datatype外键

Rails: Datatype外键
EN

Stack Overflow用户
提问于 2016-01-01 14:04:06
回答 2查看 2.3K关注 0票数 3

我有以下表格:

  • 带有主键ID的路由(ID、名称)
  • 用主键ID停止(ID,Name)
  • 映射(Route_ID,Stop_ID)

路由和Stop中的in是Mysql中的BIGINT(20)类型。迁移失败,因为使用以下命令:

代码语言:javascript
运行
复制
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

创建具有route_id和stop_id但数据类型INT(11)的表映射。这与BIGINT(20)不兼容。我怎么才能解决这个问题?有什么想法吗?创建外键失败。

错误消息

这是rake db:migrate --trace输出的一部分

**调用db:first_time **调用环境(first_time) **执行环境**调用db:load_config (first_time) **执行db:load_config **执行db:迁移== 20151227194101 CreateMappings:迁移=================================== -create_table(:映射) rake中止!StandardError:发生了一个错误,所有以后的迁移都取消了: Mysql2 2::错误:无法添加外键约束: ALTER mappings添加约束fk_rails_1b9f715271外键(route_id)引用routes (id)

当我尝试执行上面的语句时(ALTER mappings.)使用MySql客户端,我得到了以下错误:

代码语言:javascript
运行
复制
Failed to add the foreign key constaint. MIssing index for constraint 'fk_rails_1b9f715271' in the referenced table 'routes'.
EN

回答 2

Stack Overflow用户

发布于 2016-01-02 11:13:24

例如,如果不希望添加的列是整数,则references方法将接受类型选项。

代码语言:javascript
运行
复制
t.references :route, type: :bigint, index: true, foreign_key: true
票数 7
EN

Stack Overflow用户

发布于 2016-01-01 19:23:36

你试过这个表格了吗?

代码语言:javascript
运行
复制
class CreateMappings < ActiveRecord::Migration
  def change
    create_table :mappings do |t|
      t.references :route
      t.references :stop

      t.timestamps null: false
    end
  end
  add_index(:mappings, :route)
  add_index(:mappings, :stop)
end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34556792

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档