如何在 Rails 5 迁移中创建具有级联删除约束的外键?

How do I create a foreign key with a cascading delete constraint in my Rails 5 migration?

我正在使用 Rails 5 和 PostGres 9.5。我想从我的 search_codes table 创建一个到我的地址 table 的外键,所以我创建了这个迁移

class CreateSearchCodeTable < ActiveRecord::Migration[5.0]
  def change
    create_table :search_codes do |t|
      t.string :code
      t.references :address, type: :string, index: true, foreign_key: true, on_delete: :cascade
      t.index ["code"], name: "index_search_codes_on_code", unique: true, using: :btree
    end
  end
end

但是创建的内容如下。注意约束的级联部分似乎没有被创建

myapp=> \d search_codes;
                                Table "public.search_codes"
   Column   |       Type        |                         Modifiers
------------+-------------------+-----------------------------------------------------------
 id         | integer           | not null default nextval('search_codes_id_seq'::regclass)
 code       | character varying |
 address_id | character varying |
Indexes:
    "search_codes_pkey" PRIMARY KEY, btree (id)
    "index_search_codes_on_code" UNIQUE, btree (code)
    "index_search_codes_on_address_id" btree (address_id)
Foreign-key constraints:
    "fk_rails_6bd9792e3b" FOREIGN KEY (address_id) REFERENCES addresses(id)

如何使用 Rails 5 迁移和 PostGres 创建具有级联外键约束的迁移?

好像是这样ReferenceDefinition doesn't accept on_delete option. You can specify on delete with add_foreign_key:

class CreateSearchCodeTable < ActiveRecord::Migration[5.0]
  def change
    create_table :search_codes do |t|
      t.string :code
      t.references :address, type: :string, index: true
      t.index ["code"], name: "index_search_codes_on_code", unique: true, using: :btree
    end

    add_foreign_key :search_codes, :addresses, on_delete: :cascade
  end
end

从这个 link 用于 Rails 的先前版本,

这个 t.references:parent, index: true, foreign_key: {on_delete: :cascade}

似乎有效

编辑:请注意,您似乎也不需要 'index: true'。它还创建了一个索引。