使用rails migration generator添加外键

时间:2015-10-12 04:04:01

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

rails 4.2.4
ruby 2.2.1

要自动生成国家/地区迁移,我会这样做:

rails g migration CreateCountry abbreviation:string status:string search_operations_id:integer

我想在生成的迁移文件中添加一个外键:

add_foreign_key :countries, :search_operations, on_delete: :cascade

如何使用rails g migration命令执行此操作?

1 个答案:

答案 0 :(得分:0)

您可以实际上只是说:

,而不是在迁移中手动添加search_operations_id
rails g migration CreateCountry ... search_operations:references

当Rails生成迁移时,您应该看到如下内容:

class CreateCountry < ActiveRecord::Migration
  def change
    ...
    add_reference :countries, :search_operations, index: true
    add_foreign_key :countries, :search_operations
  end
end