添加 foreign_key 时出错

Error adding foreign_key

我的环境:

Ruby 2.2.1
Rails 4.2.4
mysql2 0.3.18 gem

Rails 4.2 引入 add_foreign_key。我正在尝试使用它,所以当 search_operation 被删除时,属于它的国家将从国家 table.

中删除

在我的 models/country.rb 中,我有:

class Country < ActiveRecord::Base
  belongs_to :search_operation
end

在我的 models/search_operation.rb 中,我有:

class SearchOperation < ActiveRecord::Base
  has_many :countries
end

在我的 create_countries 迁移中,我有:

class CreateCountries < ActiveRecord::Migration
  def change
    create_table :countries do |t|
      t.string :abbreviation
      t.string :status
      t.integer :search_operation_id
      t.timestamps null: false
    end
    add_foreign_key :countries, :search_operations, on_delete: :cascade
  end
end

在我的 search_operation 迁移中,我有:

class CreateSearchOperations < ActiveRecord::Migration
  def change
    create_table :search_operations do |t|
      t.string :text
      t.string :status
      t.timestamps null: false
    end
  end
end

当我 运行 耙 db:migrate 时,这是我得到的:

== 20151010195957 CreateCountries: migrating ==================================
-- create_table(:countries)
   -> 0.0064s
-- add_foreign_key(:countries, :search_operations, {:on_delete=>:cascade})
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

Mysql2::Error: Can't create table 'tracker.#sql-463_8f' (errno: 150): ALTER TABLE `countries` ADD CONSTRAINT `fk_rails_c9a545f88d`
FOREIGN KEY (`search_operation_id`)
  REFERENCES `search_operations` (`id`)
 ON DELETE CASCADE/home/trackur/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:305:in `query'

我相信我在这里使用了正确的语法。有什么想法吗?

解决方案:

确保迁移顺序是:首先创建 search_operations table,然后是使用其 id 作为外键的其他 tables。我猜 ActiveRecord 将遵循创建迁移文件的时间顺序。

确保在 countries table 之前创建 search_operations table。

如果设置外键,引用的 table 必须存在。