Ruby on Rails:数据类型外键

3

我有以下表格:

  • 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'.

什么是错误信息? - Simone Carletti
已将其添加到问题中。 - 今天春天
2个回答

8
references 方法接受一个类型选项,如果您不希望添加的列是整数类型,则可以使用该选项。例如:
t.references :route, type: :bigint, index: true, foreign_key: true

1
你尝试过这个表单吗?
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

这样做不起作用,因为route的结果数据类型将是int而不是bigint。 - 今天春天

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接