【问题标题】:Ruby on Rails: Datatype foreign keyRuby on Rails:数据类型外键
【发布时间】:2016-01-01 14:04:06
【问题描述】:

我有以下表格:

  • 带有主键 ID 的路由(ID,名称)
  • Stop(ID, Name) with Primary Key ID
  • 映射(Route_ID,Stop_ID)

Route 和 Stop 中的 ID 在 Mysql-DB 中属于 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

使用 route_id 和 stop_id 但数据类型为 INT(11) 创建一个表 Mappings。这与 BIGINT(20) 不兼容。我怎样才能解决这个问题?有任何想法吗?外键创建失败。

错误消息

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

** 调用 db:migrate (first_time) ** 调用环境(first_time) ** 执行环境 ** 调用 db:load_config (first_time) ** 执行 db:load_config ** 执行数据库:迁移 == 20151227194101 CreateMappings:迁移 =================================== -- create_table(:mappings) rake 中止! StandardError:发生错误,所有后续迁移都已取消:

Mysql2::Error: 无法添加外键约束:ALTER TABLE mappings 添加约束 fk_rails_1b9f715271 外键 (route_id) 参考资料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'.

【问题讨论】:

  • 错误信息是什么?
  • 已将其添加到问题中。

标签: mysql ruby-on-rails ruby database ruby-on-rails-4


【解决方案1】:

references 方法采用类型选项,如果您不希望添加的列是整数,例如

t.references :route, type: :bigint, index: true, foreign_key: true

【讨论】:

    【解决方案2】:

    你试过这个表格吗?

    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
    

    【讨论】:

    • 这无济于事,因为路由的结果数据类型将是 int 而不是 bigint
    猜你喜欢
    • 2021-11-23
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    相关资源
    最近更新 更多