轨道中的外键4

我正在使用Rails 4和SQLite。 我正在尝试在indicators表中添加外键。 请参阅下面的代码

 class Indicator < ActiveRecord::Base belongs_to :objetive belongs_to :responsible, class_name: "Person" end 

迁移脚本:

 class AddFksToIndicator < ActiveRecord::Migration def change add_reference :indicators, :objective, index: true add_reference :indicators, :responsible, index: true end end 

当运行迁移时一切正常,所以我尝试在控制台中:

 2.0.0p247 :002 > i = Indicator.new => # 2.0.0p247 :002 > i.objective_id = 0 2.0.0p247 :003 > i.save 

令我惊讶的是,指标已经保存,并且没有id = 0的目标。

最后,我检查了指标表模式,得到:

 CREATE TABLE "indicators" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "created_at" datetime, "updated_at" datetime, "objective_id" integer, "responsible_id" integer); CREATE INDEX "index_indicators_on_objective_id" ON "indicators" ("objective_id"); CREATE INDEX "index_indicators_on_responsible_id" ON "indicators" ("responsible_id"); 

为什么在objective_idresponsible_id上没有外键约束? 难道我做错了什么?

根据Ruby on Rails 4.2发行说明 ,只有mysql,mysql2和postgresql适配器支持外键。

不幸的是,sqlite3适配器没有。

当您使用add_reference ,您需要添加foreign_key: true以获得该调用的外键支持。 例如:

add_reference :indicators, :objective, index: true, foreign_key: true

默认值为foreign_key: false ,如此处的文档中所述。

由于您已经创建了没有外键的迁移,因此您需要通过调用add_foreign_key来创建另一个迁移。

例如:

 def change # add_foreign_key(from_table, to_table) add_foreign_key :indicators, :objectives end 

这是add_foreign_key的文档 。

希望这可以帮助。