0

我正在使用Rails 5和PostGres 9.5。我想創建從我search_codes表的外鍵到我的地址表,所以我創造了這個遷移如何使用Rails 5遷移中的級聯刪除約束創建外鍵?

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級聯的外鍵約束遷移?

回答

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 
+0

很酷。我討厭它,當應該工作的東西(如指定「on_delete」)不。 – Dave