添加foreign_key时出错

时间:2015-10-11 16:19:00

标签: ruby-on-rails ruby-on-rails-4.2

我的环境:

Ruby 2.2.1
Rails 4.2.4
mysql2 0.3.18 gem

Rails 4.2引入了add_foreign_key。我正在尝试使用它,所以当删除search_operation时,属于它的国家/地区将从国家/地区表中删除。

在我的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_operations迁移中,我有:

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

当我运行rake 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表,然后是其他使用其id作为外键的表。我想ActiveRecord将遵循创建迁移文件时的时间顺序。

1 个答案:

答案 0 :(得分:3)

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

如果设置了外键,则必须存在引用的表。