如何在Rails 5迁移中使用级联删除约束创建外键?

时间:2017-10-16 19:39:09

标签: postgresql foreign-keys migration ruby-on-rails-5 cascading-deletes

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

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创建具有级联外键约束的迁移?

2 个答案:

答案 0 :(得分:1)

似乎ReferenceDefinition不接受on_delete选项。您可以使用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

答案 1 :(得分:0)

通过此链接可获取先前版本的Rails, Option for Cascade Delete for References or On Delete

这 t.references:parent,index:true,外键:{on_delete::cascade}

似乎可以工作

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